package com.rds.workflow.controller;

import com.alibaba.fastjson.JSONObject;
import com.rds.common.annotation.RepeatSubmit;
import com.rds.common.constant.HttpStatus;
import com.rds.common.core.controller.BaseController;
import com.rds.common.core.domain.AjaxResult;
import com.rds.common.core.domain.entity.Document;
import com.rds.common.core.domain.entity.Folder;
import com.rds.common.core.domain.entity.SysRole;
import com.rds.common.core.domain.entity.SysUser;
import com.rds.common.core.page.TableDataInfo;
import com.rds.common.core.redis.RedisCache;
import com.rds.common.core.service.IDynamicService;
import com.rds.common.mail.EmailUser;
import com.rds.common.mail.MailConfig;
import com.rds.common.utils.DateUtils;
import com.rds.common.utils.EmailUtil;
import com.rds.common.utils.SecurityUtils;
import com.rds.common.utils.uuid.SnowFlakeUtils;
//import com.rds.system.common.history.HistoryRecordUtil;
import com.rds.system.domain.*;
import com.rds.system.service.*;

import com.rds.workflow.domain.*;
import com.rds.workflow.lifecycle.WorkFlowLifeCycleUtil;
import com.rds.workflow.lifecycle.WorkspaceUtils;
import com.rds.workflow.service.*;
import com.rds.workflow.utils.WorkflowSharing;
import com.rds.workflow.utils.WorkflowStateid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/pms/workflow")
public class RdaWorkflowController extends BaseController {

    @Autowired
    private IDynamicService dynamicService;
    @Autowired
    private IRdaStateService rdaStateService;
    @Autowired
    private ISysHistoryService sysHistoryService;
    @Autowired
    private IRdaWorkflowService rdaWorkflowService;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private IRdaWfNodeService rdaWfNodeService;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private IRdaWfTaskService rdaWfTaskService;
    @Autowired
    private IRdaNode2TaskRelService rdaNode2TaskRelService;
    @Autowired
    private IRdaWorkflow2NodeRelService rdaWorkflow2NodeRelService;
    @Autowired
    private IRdaWorkflowTempleteService rdaWorkflowTempleteService;
    @Autowired
    private RdaWorkflowObjectRelService rdaWorkflowObjectRelService;
    @Autowired
    private ISysRoleService roleService;
    /*@Autowired
    private IRdaFolderRelService rdaFolderRelService;*/
    @Autowired
    private IRdaWfNodeAgentRelService rdaWfNodeAgentRelService;
    @Autowired
    private IRdaWfUserAgentService rdaWfUserAgentService;
    @Autowired
    private IRdaTypeService rdaTypeService;
    @Autowired
    private IRdaWorkflowDynamicattributevalueService rdaWorkflowDynamicattributevalueService;
    @Autowired
    private IRdaWorkflowDynamicattributeService rdaWorkflowDynamicattributeService;
    /*@Autowired
    private IRdaProjectWorkflowService rdaProjectWorkflowService;*/
    @Autowired
    private EmailUtil emailUtil;
    @Autowired
    private IRdaPolicyService rdaPolicyService;
    @Autowired
    private MailConfig mailConfig;

    /**
     * 流程列表类型
     * 以下注释后期可删除
     * 开发人员数据库数据:10000954(Workflow)[类型]
     * 测试数据库数据:10000807
     */
    //public final  static Long workflowTypeid = 10000807L;

    /**
     * 流程列表策略
     * 以下注释后期可删除
     * 开发人员数据库数据:10000964(WorkflowList)[策略]
     * 测试数据库数据:10000814
     */
    //public final  static Long workflowPolicyid = 10000814L;


    /**
     * 流程节点完成状态
     * 以下注释后期可删除
     * 开发人员数据库数据:10000937(Complete)-->>10000934[WorkflowNodeTemplete]
     * 测试数据库数据:10000828(Complete)-->10000815(WorkflowNodeTemplete)[10000827(作废)-10000830(创建)]
     */
    //public final  static Long nodeStateAppoveid = 10000828L;

    /*以下节点状态均属于策略WorkflowNodeTemplete(10000815)****/
    /**
     * 流程节点取消状态
     */
    //public final  static Long nodeStateCancelid = 10000827L;

    //public final  static Long nodeStateCreateid = 10000830L;
    /**
     * 流程节点活动状态
     */
    //public final  static Long nodeStateActiveid = 10000829L;


    /**
     * 流程任务创建状态
     */
    //public final  static Long taskStateCreateid=10001012l;

    /**
     * 流程任务完成状态
     */
    //public final  static Long taskStateAppoveid = 10000828L;

    /**
     * 流程任务取消状态
     */
    //public final  static Long taskStateCancelid = 10000827L;

    /**
     * 流程任务活动状态
     */
    //public final  static Long taskStateActiveid=10000821L;

    /**
     * 流程任务完成状态
     */
    //public final  static Long taskStateCompleteid=10001014l;

    /**
     * 流程任务作废状态
     */
    //public final  static Long taskStateObsoletedid = 10000819L;



    /**
     * 流程对象完成状态
     * 对应策略(WorkflowList)
     * 10000967(Complete)
     */
    //public final  static Long WFStateAppoveid = 10000824L;

    /**
     * 流程对象取消状态
     */
    //public final  static Long WFStateCancelid=10000824L;

    /**
     * 流程对象活动状态
     */
    //public final  static Long WFStateActiveid=10000966l;

    /**
     * 流程列表创建状态
     * 对应策略(WorkflowList)
     * 10000965(创建)
     */
    //public final static Long workflowCreateid = 10000826L;

    /**
     * 流程列表活动状态
     */
    //public final static Long workflowActiveid=10000966l;

    /**
     * 流程列表完成状态
     */
    //public final static Long workflowCompleteid=10000824L;

    /**
     * 流程列表作废状态
     */
    //public final static Long workflowObsoleted=10000968l;

    /**
     * 流程列表节点类型创建状态
     */
    //public final static Long wfNodeCreateid=10000818l;

    /**
     * 流程列表节点类型活动状态
     */
    //public final static Long wfNodeActiveid=10000817l;

    /**
     * 流程列表节点类型完成状态
     */
    //public final static Long wfNodeCompleteid=10001108l;

    /**
     * 流程列表节点类型作废状态
     */
    //public final static Long wfNodeObsoleteid=10001109l;


    /**
     * 查询流程模板列表
     */
    @PreAuthorize("@ss.hasPermi('pms:workflow:workflowList')")
    @GetMapping("/workflowList")
    public TableDataInfo workflowList(RdaWorkflow rdaWorkflow){
        startPage();
        return getDataTable(rdaWorkflowService.selectRdaWorkflowist(rdaWorkflow));
    }

    /**
     * 获取流程列表详细信息
     */
    @PreAuthorize("@ss.hasPermi('pms:workflow:query')")
    @GetMapping(value = "/template/{id}")
    public AjaxResult getTemplateInfo(@PathVariable("id") Long id){
        return AjaxResult.success(rdaWorkflowService.selectRdaWorkflowById(id));
    }

    /**
     * 获取流程列表详细信息
     */
    @PreAuthorize("@ss.hasPermi('pms:workflow:modifyWorkflowList')")
    @GetMapping(value = "/modifyWorkflowList/{id}")
    public AjaxResult modifyWorkflowList(@PathVariable("id") Long id){
        return AjaxResult.success(rdaWorkflowService.selectRdaWorkflowById(id));
    }

    /**
     * 获取流程列表详细信息
     */
    @PreAuthorize("@ss.hasPermi('pms:workflow:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(rdaWorkflowService.selectRdaWorkflowById(id));
    }

    /**
     * 查询流程模板节点拒绝列表
     */
    @PreAuthorize("@ss.hasPermi('pms:workflow:nodeRefuseList')")
    @GetMapping("/nodeRefuseList")
    public TableDataInfo nodeRefuseList(RdaWfNode rdaWfNode){
        startPage();
        return getDataTable(rdaWorkflow2NodeRelService.selectRdaWorkflow2NodeRelByOperationType(rdaWfNode.getWorkflowid(),"Reject"));
    }

    /**
     * 新增流程列表
     */
    /*@PreAuthorize("@ss.hasPermi('pms:workflow:addWorkflow')")
    @PostMapping("/addWorkflow")
    @Transactional
    public AjaxResult addWorkflow(@RequestBody RdaWorkflow rdaWorkflow){
        Long id= SnowFlakeUtils.nextId();
        rdaWorkflow.setId(id);
        rdaWorkflow.setOwnerid(SecurityUtils.getUserId().intValue());
        rdaWorkflow.setTypeid(WorkflowStateid.workflowTypeid.intValue());
        rdaWorkflow.setPolicyid(WorkflowStateid.workflowPolicyid.intValue());
        rdaWorkflow.setStateid(WorkflowStateid.workflowCreateid.intValue());
        //保存动态分类属性 rda_workflow_dynamicattributevalue
        //区分是否是动态属性用typeid=流程分类id查询rda_workflow_dynamicattribute；
        int rows=rdaWorkflowService.insertRdaWorkflow(rdaWorkflow);

        return toAjax(rows);
    }*/
    @PreAuthorize("@ss.hasPermi('pms:workflow:addWorkflow')")
    @PostMapping("/addWorkflow")
    @Transactional
    public AjaxResult addWorkflow(@RequestBody JSONObject jsonParam){
        RdaWorkflow rdaWorkflow=new RdaWorkflow();
        Long id= SnowFlakeUtils.nextId();
        Long typeid = null;
        ArrayList<String> attribute_key=new ArrayList<String>();//临时存储json键
        ArrayList<String> attribute_value=new ArrayList<String>();//临时存储json值
        // 直接将json信息打印出来
        System.out.println(jsonParam.toJSONString());
        //将json转换成map循环取键值对
        Map<String, Object> map =jsonParam;
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            String attributeValue=(String)entry.getValue();
            if(attributeValue!=null && attributeValue.length()!=0){
                System.out.println(entry.getKey()+"="+entry.getValue());
                if(entry.getKey().equals("name")){
                    rdaWorkflow.setName(attributeValue);
                }else if(entry.getKey().equals("description")){
                    rdaWorkflow.setDescription(attributeValue);
                }else if(entry.getKey().equals("flowTempleteid")){
                    rdaWorkflow.setFlowTempleteid(Long.valueOf(attributeValue));
                }else if(entry.getKey().equals("typeid")){
                    typeid=Long.parseLong(attributeValue);
                }else{
                    attribute_key.add(entry.getKey());
                    attribute_value.add(attributeValue);
                }
            }
        }
        //区分是否是动态属性用typeid=流程分类id查询rda_workflow_dynamicattribute；
        for(int i=0;i<attribute_key.size();i++){
            RdaWorkflowDynamicattribute rdaWorkflowDynamicattribute=new RdaWorkflowDynamicattribute();
            rdaWorkflowDynamicattribute.setTypeid(typeid);
            rdaWorkflowDynamicattribute.setAttributeName(attribute_key.get(i));
            List<RdaWorkflowDynamicattribute> workflowDynamicattributeList=rdaWorkflowDynamicattributeService.selectRdaWorkflowDynamicattributeList(rdaWorkflowDynamicattribute);
            for(int j=0;j<workflowDynamicattributeList.size();j++){
                RdaWorkflowDynamicattribute workflowDynamicattribute=workflowDynamicattributeList.get(j);
                Long dynamicattributeId=workflowDynamicattribute.getId();

                RdaWorkflowDynamicattributevalue rdaWorkflowDynamicattributevalue = new RdaWorkflowDynamicattributevalue();
                rdaWorkflowDynamicattributevalue.setId(SnowFlakeUtils.nextId());
                rdaWorkflowDynamicattributevalue.setOwnerid(SecurityUtils.getUserId());
                rdaWorkflowDynamicattributevalue.setDynamicattributeid(dynamicattributeId);
                rdaWorkflowDynamicattributevalue.setCreateTime(DateUtils.getNowDate());
                rdaWorkflowDynamicattributevalue.setObjectid(id);
                rdaWorkflowDynamicattributevalue.setAttributeValue(attribute_value.get(i));
                rdaWorkflowDynamicattributevalueService.insertRdaWorkflowDynamicattributevalue(rdaWorkflowDynamicattributevalue);
            }
        }
        rdaWorkflow.setId(id);
        rdaWorkflow.setOwnerid(SecurityUtils.getUserId().intValue());
        rdaWorkflow.setTypeid(WorkflowStateid.workflowTypeid.intValue());
        rdaWorkflow.setPolicyid(WorkflowStateid.workflowPolicyid.intValue());
        rdaWorkflow.setStateid(WorkflowStateid.workflowCreateid.intValue());
        rdaWorkflow.setAssignmentypeid(typeid);
        //后续改成查询流程模板根据assignmentypeid查询
        int rows=0;
        rows=rdaWorkflowService.insertRdaWorkflow(rdaWorkflow);
//        new HistoryRecordUtil(sysHistoryService).recordHistory(id,"创建",rdaWorkflow.getStateid(),"流程列表","");
        return toAjax(rows);
    }

    /**
     * 删除流程列表
     */
    @PreAuthorize("@ss.hasPermi('pms:workflow:removeWorkflowList')")
    @DeleteMapping("/removeWorkflowList/{ids}")
    @Transactional
    public AjaxResult removeWorkflowList(@PathVariable Long[] ids){
        for(int i=0;i<ids.length;i++){
            RdaWorkflow getStateid = rdaWorkflowService.selectRdaWorkflowById(ids[i]);
            Long stateid = getStateid.getStateid().longValue();
            if (!stateid.equals(WorkflowStateid.workflowCreateid)) {
                return AjaxResult.error("抱歉该流程已启动，无法进行删除,无法删除的流程名有："+getStateid.getName());
            }else{
                rdaWfNodeService.deleteRdaWfNodeByWorkflowid(ids[i]);
                rdaWorkflow2NodeRelService.deleteRdaWorkflow2NodeRelByWorkflowid(ids[i]);
                rdaNode2TaskRelService.deleteRdaNode2TaskRelByWorkflowid(ids[i]);
                rdaWfTaskService.deleteRdaWfTaskByWorkflowid(ids[i]);
                rdaWorkflowObjectRelService.deleteRdaWorkflowObjectRelWorkflowid(ids[i]);
            }

        }
        return toAjax(rdaWorkflowService.deleteRdaWorkflowByIds(ids));
    }

    /**
     * 修改流程模板
     */
    @PreAuthorize("@ss.hasPermi('pms:workflow:template')")
    @PutMapping("/template")
    @Transactional
    public AjaxResult updateWorkflowList(@RequestBody RdaWorkflow rdaWorkflow){
        RdaWorkflow workflow=rdaWorkflowService.selectRdaWorkflowById(rdaWorkflow.getId());
        return toAjax(rdaWorkflowService.updateRdaWorkflow(rdaWorkflow));
    }

    /**
     * 修改流程模板
     */
    @PreAuthorize("@ss.hasPermi('pms:workflow:modifyWorkflowList')")
    @PutMapping("/modifyWorkflowList")
    @Transactional
    public AjaxResult modifyWorkflowList(@RequestBody RdaWorkflow rdaWorkflow){
        RdaWorkflow workflow=rdaWorkflowService.selectRdaWorkflowById(rdaWorkflow.getId());
        return toAjax(rdaWorkflowService.updateRdaWorkflow(rdaWorkflow));
    }

    /**
     * 查询流程模板节点图列表
     */
    @PreAuthorize("@ss.hasPermi('pms:workflow:nodeFlowChartList')")
    @GetMapping("/nodeFlowChartList")
    public AjaxResult nodeFlowChartList(RdaWfNode rdaWfNode){
        startPage();
        Map<String,Object> info = new HashMap<>();
        List<RdaWfNode> ApproveList=rdaWfNodeService.selectRdaWfNodeTemplete(rdaWfNode.getWorkflowid(),"Approve");
        List<RdaWorkflow2NodeRel> RejectList=rdaWorkflow2NodeRelService.selectRdaWorkflow2NodeRelByOperationType(rdaWfNode.getWorkflowid(),"Reject");
        RdaWfTask rdaWfTask=new RdaWfTask();
        rdaWfTask.setWorkflowid(rdaWfNode.getWorkflowid());
        List<RdaWfTask> taskList=rdaWfTaskService.selectRdaWfTaskList(rdaWfTask);
        RdaWorkflow2NodeRel rdaWorkflow2NodeRel=new RdaWorkflow2NodeRel();
        rdaWorkflow2NodeRel.setWorkflowid(rdaWfNode.getWorkflowid());
        List<RdaWorkflow2NodeRel> workflow2NodeRelList=rdaWorkflow2NodeRelService.selectRdaWorkflow2NodeRelAllList(rdaWorkflow2NodeRel);
        info.put("nodeList",ApproveList);
        info.put("Reject",RejectList);
        info.put("task",taskList);
        info.put("workflowPath",workflow2NodeRelList);
        return AjaxResult.success(info);
    }

    /**
     * 查询流程模板节点列表
     */
    @PreAuthorize("@ss.hasPermi('pms:workflow:nodeList')")
    @GetMapping("/nodeList")
    public TableDataInfo nodeList(RdaWfNode rdaWfNode){
        startPage();
        List<RdaWfNode> ApproveList=rdaWfNodeService.selectRdaWfNodeTemplete(rdaWfNode.getWorkflowid(),"Approve");
        return getDataTable(ApproveList);
    }

    /**
     * 添加人员
     */
    @PreAuthorize("@ss.hasPermi('pms:workflow:assignWorkflow')")
    @PostMapping("/assignWorkflow")
    public AjaxResult assignWorkflow(@RequestBody Sharing sharing){
        RdaWfNode rdaWfNode=rdaWfNodeService.selectRdaWfNodebyById( Long.parseLong(sharing.getToid()));

        String idsStr=sharing.getIds();
        String[] ids =idsStr.split(",");
        String[] nodeids =sharing.getToid().split(",");
        RdaWfNode rdaWfNode2=new RdaWfNode();
        rdaWfNode2.setId(Long.valueOf(nodeids[0]));
        rdaWfNode2.setUserId(idsStr);
        int row=0;
        if(WorkflowStateid.wfNodeCreateid.equals(rdaWfNode.getStateid().longValue())){
             row=rdaWfNodeService.updateRdaWfNode(rdaWfNode2);
            return toAjax(row);
        }else if(WorkflowStateid.wfNodeActiveid.equals(rdaWfNode.getStateid().longValue())){
             row=rdaWfNodeService.updateRdaWfNode(rdaWfNode2);
            rdaWfTaskService.updateRdaWfTaskPersonnel(Long.valueOf(ids[0]),rdaWfNode.getId(),WorkflowStateid.wfTaskActiveid,rdaWfNode.getWorkflowid());
        }else {
            return  error("当前节点不是创建状态跟活动状态，无法指派人员");
        }

        return toAjax(row);
    }

    /**
     * 启动流程
     */
    @PreAuthorize("@ss.hasPermi('pms:workflow:startUpWorkflowList')")
    @GetMapping("/startUpWorkflowList/{ids}")
    @Transactional
    public AjaxResult startUpWorkflowList(@PathVariable Long[] ids){
        for (int i=0;i<ids.length;i++) {
            Long objectUserId=null;
            RdaWorkflowObjectRel rdaWorkflowObjectRel=new RdaWorkflowObjectRel();
            rdaWorkflowObjectRel.setWorkflowid(ids[i]);
            List<RdaWorkflowObjectRel> objectList=rdaWorkflowObjectRelService.selectRdaWorkflowObjectRelList(rdaWorkflowObjectRel);
            if(objectList!=null &&objectList.size()>0){
                String checkTips=objectCheck(rdaWorkflowObjectRel=objectList.get(0),"文档启动流程");
                if(!checkTips.isEmpty()){
                    return AjaxResult.error(checkTips);
                }

                if("document".equals(objectList.get(0).getObjectModuleName())){
                    HashMap<String,Object> documentPage=dynamicService.selectDataById("rda_document",objectList.get(0).getObjectid());

                    if(documentPage!=null){
                        objectUserId=Long.valueOf(documentPage.get("ownerid").toString());
                    }
                }
            }
            RdaWorkflow getStateid = rdaWorkflowService.selectRdaWorkflowById(ids[i]);
            Long stateid = getStateid.getStateid().longValue();
            if (!stateid.equals(WorkflowStateid.workflowCreateid)) {
                return AjaxResult.error("当前任务已启动，请勿重复启动");
            }
            RdaWfNode wfNode = new RdaWfNode();
            wfNode.setWorkflowid(ids[i]);
            wfNode.setNodeType(1);
            List<RdaWfNode> WfNodeList = rdaWfNodeService.selectRdaWfNodeList(wfNode);
            String nodeNames = "";
            for (RdaWfNode rdaWfNode : WfNodeList) {
                if (rdaWfNode.getUserId() == null || "".equals(rdaWfNode.getUserId())) {
                    nodeNames += rdaWfNode.getNodeName() + ",";
                }
            }
            if (!nodeNames.isEmpty()) {
                return AjaxResult.error("当前任务有节点未指定用户，启动失败，未设置用户的节点名有：" + nodeNames.substring(0, nodeNames.lastIndexOf(",")));
            }

            RdaWorkflow rdaWorkflow = new RdaWorkflow();
            rdaWorkflow.setId(ids[i]);
            /*2021-12-19 以后要更换成动态**/
            rdaWorkflow.setStateid(WorkflowStateid.workflowActiveid.intValue());
            rdaWorkflow.setModifyTime(DateUtils.getNowDate());
            //把流程状态设置为活动
            rdaWorkflowService.updateRdaWorkflow(rdaWorkflow);
//            new HistoryRecordUtil(rdaStateService,sysHistoryService).lifeCycleHistory(rdaWorkflow.getId(),WorkflowStateid.workflowCreateid.intValue(),rdaWorkflow.getStateid(),"promote");

            //将流程开始节点设置为完成状态

            /*2021-12-19 以后要更换成动态**/
//            rdaWfNodeService.updateRdaWfNodeByStateid(ids[i],10000828L,0l);
            rdaWfNodeService.updateRdaWfNodeByStateid(ids[i], WorkflowStateid.wfNodeCompleteid, 0L,DateUtils.getNowDate());
            //将下节点设置为活动状态

            RdaWfNode startNode = rdaWfNodeService.selectRdaWfNodeStartOrEnd(ids[i], 0l);
            RdaWorkflow2NodeRel rdaWorkflow2NodeRel = new RdaWorkflow2NodeRel();
            rdaWorkflow2NodeRel.setFromid(startNode.getId());
            List<RdaWorkflow2NodeRel> startList = rdaWorkflow2NodeRelService.selectRdaWorkflow2NodeRelList(rdaWorkflow2NodeRel);
            for (int j = 0; j < startList.size(); j++) {
                //更新开始节点下级节点为活动
                RdaWfNode modifyStateid = new RdaWfNode();
                modifyStateid.setId(startList.get(j).getToid());
                modifyStateid.setStateid(WorkflowStateid.wfNodeActiveid.intValue());
                modifyStateid.setStartTime(DateUtils.getNowDate());
                rdaWfNodeService.updateRdaWfNode(modifyStateid);


                List<RdaWfNode> list = rdaWfNodeService.selectRdaWfNodebyUser(startList.get(j).getToid());
                if (list != null) {
                    for (RdaWfNode rdaWfNode : list) {
                        String[] userId=rdaWfNode.getUserId().split(",");
                        for(int k=0;k<userId.length;k++) {
                            String userIdK=userId[k];
                            Long userIdJ=Long.valueOf(userIdK);
                            SysUser user = userService.selectUserById(userIdJ);

                            RdaWfTask rdaWfTask = new RdaWfTask();
                            Long id = SnowFlakeUtils.nextId();
                            rdaWfTask.setId(id);
                            rdaWfTask.setWorkflowid(ids[i]);
                            rdaWfTask.setNodeid(rdaWfNode.getId());
                            //2022-02-11 通过流程启动判断该流程是否是全局委托 start
                            if (workflowAgent(rdaWfNode)) {
                                return toAjax(1);
                            }
                            //2022-02-11 通过流程启动判断该流程是否是全局委托 end
                            if (user != null) {
                                rdaWfTask.setTaskName(rdaWfNode.getNodeName() + "的任务");
                                rdaWfTask.setDescription(rdaWfNode.getNodeName() + "的任务");
                            }
                            rdaWfTask.setUserId(userIdJ);
                            rdaWfTask.setOwnerid(SecurityUtils.getUserId());

                            rdaWfTask.setTypeid(WorkflowStateid.wfTaskTypeid);
                            rdaWfTask.setPolicyid(WorkflowStateid.wfTaskPolicyid);
                            rdaWfTask.setStateid(WorkflowStateid.wfTaskActiveid);
                            rdaWfTask.setTransfer(false);
                            rdaWfTask.setOriginalId(userIdJ);
                            rdaWfTask.setCreateTime(DateUtils.getNowDate());
                            rdaWfTask.setStartTime(DateUtils.getNowDate());
                            rdaWfTaskService.insertRdaWfTask(rdaWfTask);
                            //还剩关系表未插入、待完成rda_node2_task_rel
                            RdaNode2TaskRel rdaNode2TaskRel = new RdaNode2TaskRel();
                            rdaNode2TaskRel.setId(SnowFlakeUtils.nextId());
                            rdaNode2TaskRel.setTaskid(rdaWfTask.getId());
                            rdaNode2TaskRel.setNodeid(rdaWfNode.getId());
                            rdaNode2TaskRelService.insertRdaNode2TaskRel(rdaNode2TaskRel);
                            //自动节点处理
                            boolean automaticCheck = automaticNodeMethod(rdaWfNode.getId(), ids[i], "自动同意");
                            if(automaticCheck){
                                break;
                            }
                            if(objectUserId!=null) {
                                //当流程节点用户名跟流程接口业务用户名相同时则启动下一节点
                                if (userIdK.contains(objectUserId.toString())) {
                                    //将当前节点设置为完成状态，启动下一节点
                                    RdaWfTask rdaWfTaskI = new RdaWfTask();
                                    rdaWfTaskI.setId(id);
                                    rdaWfTaskI.setApproveExplain("由于当前任务在你名下故自动同意");
                                    rdaWfTaskI.setApprove("approve");
                                    myWFTaskAppoveAgree(rdaWfTaskI.getId(), rdaWfTaskI.getApproveExplain(), rdaWfTaskI);
                                }
                            }
                        }
                    }
                }
            }
        }
        return toAjax(1);
    }

    /**
     * 流程审批详情页
     */
    @PreAuthorize("@ss.hasPermi('pms:workflow:myWFTaskAppove')")
    @GetMapping("/myWFTaskAppove/{id}")
    public AjaxResult myWFTaskAppove(@PathVariable("id") Long id){
        RdaWfTask rdaWfTask=rdaWfTaskService.selectRdaWfTaskByid(id);
//        if(rdaWfTask.getStateid().equals(nodeStateAppoveid)){
        if(rdaWfTask.getStateid().equals(WorkflowStateid.wfTaskCompleteid)){
            return AjaxResult.error("当前节点已完成无需继续操作");
        }
        rdaWfTask.setApproveExplain("");
        return AjaxResult.success(rdaWfTask);
    }

    /**
     * 流程审批详情信息
     */
    @PreAuthorize("@ss.hasPermi('pms:workflow:myWFTaskReview')")
    @GetMapping("/myWFTaskReview/{taskId}")
    @Transactional
    public AjaxResult Review(@PathVariable("taskId") Long taskId){
        ArrayList<Map> rejectList=new ArrayList<Map>();
        ArrayList<Map> approveList=new ArrayList<Map>();
        Map<String,String>  rdaWfNodeList=new HashMap<String,String>();
        Map<String,String>  approveMap=new HashMap<String,String>();
        //通过任务id获取当前节点id
        Map<String,Object> info = new HashMap<>();
        RdaWfTask rdaWfTask=rdaWfTaskService.selectRdaWfTaskByid(taskId);
        Long nodeid=rdaWfTask.getNodeid();
        Long workflowid=rdaWfTask.getWorkflowid();
        RdaWfNode rdaWfNode=rdaWfNodeService.selectRdaWfNodebyById(nodeid);//当前节点
        RdaWorkflow rdaWorkflow=rdaWorkflowService.selectRdaWorkflowById(workflowid);
        info.put("workflow",rdaWorkflow);
        info.put("task",rdaWfTask);

        boolean rejectTostart=rdaWfNode.isRejectTostart();
        if(rejectTostart){
            rdaWfNodeList.put("Reject_toStart","开始节点");
        }
        //2022-02-28 流程分支管理查询 start
        List<RdaWorkflow2NodeRel> workflow2NodeRelList=rdaWorkflow2NodeRelService.selectRdaWorkflow2NodeRelByFromid(nodeid,workflowid,"Approve");
        for(RdaWorkflow2NodeRel rdaWorkflow2NodeRel:workflow2NodeRelList){
            if(rdaWorkflow2NodeRel.getRoad()!=null && rdaWorkflow2NodeRel.getRoad().length()>0){
                Long toid=rdaWorkflow2NodeRel.getToid();
                Long id=rdaWorkflow2NodeRel.getId();
                if("人工路径".equals(rdaWorkflow2NodeRel.getRoad())){
                    approveMap.put("Approve_"+toid.toString()+"_"+id,rdaWorkflow2NodeRel.getRoadFlag());
                }
            }
        }
        //2022-02-28 流程分支管理查询 end

        //boolean rejectSkipComplete=rdaWfNode.isRejectSkipComplete();
        List<RdaWorkflow2NodeRel> rdaWorkflow2NodeRelList =rdaWorkflow2NodeRelService.selectRdaWorkflow2NodeRelByFromids(nodeid,workflowid,"Reject","0");
        for(RdaWorkflow2NodeRel rdaWorkflow2NodeRel:rdaWorkflow2NodeRelList){
            Long toid=rdaWorkflow2NodeRel.getToid();
            Long id=rdaWorkflow2NodeRel.getId();
            RdaWfNode rdaWfNode2=rdaWfNodeService.selectRdaWfNodebyById(toid);

            String nodeName=rdaWfNodeList.get("Reject_toStart");
            if(nodeName!=null){
                if(!nodeName.equals(rdaWfNode2.getNodeName())){
                    rdaWfNodeList.put("Reject_"+toid.toString()+"_"+id,rdaWfNode2.getNodeName());
                }
            }else{
                rdaWfNodeList.put("Reject_"+toid.toString()+"_"+id,rdaWfNode2.getNodeName());
            }

        }
        if(rdaWfNodeList!=null && rdaWfNodeList.size()!=0){
            rejectList.add(rdaWfNodeList);
        }

        if(approveMap!=null && approveMap.size()!=0){
            approveList.add(approveMap);
        }
        RdaWorkflowObjectRel rdaWorkflowObjectRel=new RdaWorkflowObjectRel();
        rdaWorkflowObjectRel.setWorkflowid(workflowid);
        List<RdaWorkflowObjectRel> workflowObjectRelList=rdaWorkflowObjectRelService.selectRdaWorkflowObjectRelList(rdaWorkflowObjectRel);
        workflowObjectRelList.forEach((RdaWorkflowObjectRel workflowObjectRel)->{
            if("reimbursement".equals(workflowObjectRel.getObjectModuleName()) ||"airticketApply".equals(workflowObjectRel.getObjectModuleName())){
                info.put("rejectSkipComplete",true);
            }else{
                info.put("rejectSkipComplete",false);
            }
        });
        if(rejectList!=null && rejectList.size()!=0){
            info.put("reject",rejectList);
        }

        if(approveList!=null && approveList.size()!=0){
            info.put("approve",approveList);
        }
        return AjaxResult.success(info);
    }

    /**
     * 流程审批
     */
    @PreAuthorize("@ss.hasPermi('pms:workflow:myWFTaskAppove')")
    @PutMapping("/myWFTaskAppove")
    @Transactional
    @RepeatSubmit
    public AjaxResult myWFTaskAppove(@RequestBody RdaWfTask rdaWfTask){
        String approveExplain=rdaWfTask.getApproveExplain();
        if(rdaWfTask.getApprove()!=null && rdaWfTask.getApprove().length()>0){

                //2022-02-10 判断流程委托状态start
                RdaWfTask rdaWfTask2=rdaWfTaskService.selectRdaWfTaskByid(rdaWfTask.getId());
                if("抄送".equals(rdaWfTask2.getAgentTypeid())){
                    return error("当前为被委托人，无权操作");
                }
                //2022-02-10 判断流程委托状态 end
                myWFTaskAppoveAgree(rdaWfTask.getId(),approveExplain,rdaWfTask);

        }else if(rdaWfTask.getReject()!=null && rdaWfTask.getReject().length()>0){
            //更新跳过已完成节点跟暂停
            if(rdaWfTask.isSkipComplete()) {
                myWFTaskAppoveRefuseSkipComplete(rdaWfTask.getId(), approveExplain, rdaWfTask.getReject(), rdaWfTask);
            }else{
                myWFTaskAppoveRefuse(rdaWfTask.getId(), approveExplain, rdaWfTask.getReject(), rdaWfTask);
            }
        }
        return toAjax(1);
    }

    /**
     * 流程拒绝：跳过已完成
     */
    public AjaxResult myWFTaskAppoveRefuseSkipComplete(Long ids,String approveExplain,String refuseType,RdaWfTask task){
        RdaWfTask rdaWfTask=new RdaWfTask();
        RdaWfNode rdaWfNode = new RdaWfNode();
        // 根据当前任务id查询当前nodeid
        RdaWfTask rdaWfTask2=rdaWfTaskService.selectRdaWfTaskByid(ids);// rda_wf_task where id=#{id}
        Long nodeid=rdaWfTask2.getNodeid();

        //获取流程id
        Long workflowid=rdaWfTask2.getWorkflowid();//流程id

        //4 修改流程版本，版本号加1
        RdaWorkflow rdaWorkflow=new RdaWorkflow();
        RdaWorkflow rdaWorkflow2=rdaWorkflowService.selectRdaWorkflowById(workflowid);
        String revision=rdaWorkflow2.getRevision();//获取当前版本号
        if(revision==null){
            revision="0";
        }
        Integer VersionNumber=Integer.parseInt(revision);
        Integer revisionNumber=VersionNumber+1;
        rdaWorkflow.setId(rdaWorkflow2.getId());
        rdaWorkflow.setRevision(""+revisionNumber);
        //设置流程新的版本号
        rdaWorkflowService.updateRdaWorkflow(rdaWorkflow);

        //设置当前任务策略为暂停，状态为暂停，响应类型为拒绝；
        rdaWfTask.setId(ids);
        rdaWfTask.setStateid(WorkflowStateid.wfTaskSuspendid);
        rdaWfTask.setApproveExplain(approveExplain);
        rdaWfTask.setOperId("拒绝");
        rdaWfTaskService.updateRdaWfTask(rdaWfTask);

        //设置当前节点策略为暂停，状态为暂停，响应类型为拒绝；
        rdaWfNode.setId(nodeid);
        rdaWfNode.setStateid(WorkflowStateid.wfNodeSuspendid.intValue());
        rdaWfNode.setResponseType("拒绝");
        rdaWfNodeService.updateRdaWfNode(rdaWfNode);

        //查询当前节点的其他活动任务，并将其策略为暂停，状态为暂停；
        RdaWfTask rdaWfTaskNodeid=new RdaWfTask();
        rdaWfTaskNodeid.setNodeid(nodeid);
        rdaWfTaskNodeid.setStateid(WorkflowStateid.wfTaskActiveid);
        rdaWfTaskNodeid.setWorkflowid(workflowid);
        List<RdaWfTask> taskList=rdaWfTaskService.selectRdaWfTaskByStateId(rdaWfTaskNodeid);
        for(RdaWfTask rdaWfTaskt:taskList){
            rdaWfTask=new RdaWfTask();
            rdaWfTask.setId(rdaWfTaskt.getId());
            rdaWfTask.setStateid(WorkflowStateid.wfTaskSuspendid);
            rdaWfTaskService.updateRdaWfTask(rdaWfTask);
        }

        //查询流程中的其他活动任务，将其策略为暂停，状态为暂停；
        rdaWfTask=new RdaWfTask();
        rdaWfTask.setWorkflowid(workflowid);
        rdaWfTask.setStateid(WorkflowStateid.wfTaskActiveid);
        rdaWfTask.setToolbarType("1");
        List<RdaWfTask> wfTaskList=rdaWfTaskService.selectRdaWfTaskList(rdaWfTask);
        for(RdaWfTask rdaWfTaskt:wfTaskList){
            rdaWfTask=new RdaWfTask();
            rdaWfTask.setId(rdaWfTaskt.getId());
            rdaWfTask.setStateid(WorkflowStateid.wfTaskSuspendid);
            rdaWfTaskService.updateRdaWfTask(rdaWfTask);
        }

        //查询流程中的其他活动节点，将其策略为暂停，状态为暂停；
        // 同时收集到集合ActiveNodes中
        // 设置版本为当前流程版本revisionNumber；
        //2.2 活动节点和创建节点处理
        //a 查询该流程所有活动状态的节点的活动任务；将其状态重置为暂停状态；
        rdaWfTask = new RdaWfTask();
        rdaWfTask.setWorkflowid(workflowid);
        rdaWfTask.setStateid(WorkflowStateid.wfTaskActiveid);
        rdaWfTask.setToolbarType("1");
        List<RdaWfTask> rdaWfTaskList = rdaWfTaskService.selectRdaWfTaskList(rdaWfTask);//根据流程id查询所有活动状态的任务
        //将所有活动状态的任务更改为暂停状态
        for (RdaWfTask rdaWfTask3 : rdaWfTaskList) {
            Long taskId = rdaWfTask3.getId();
            rdaWfTask3 = new RdaWfTask();
            rdaWfTask3.setId(taskId);
            rdaWfTask3.setStateid(WorkflowStateid.wfTaskSuspendid);
            rdaWfTaskService.updateRdaWfTask(rdaWfTask3);
        }
        String AffectedNodeids =nodeid.toString();
        // b 查询该流程所有活动状态的节点（收集到集合ActiveNodes）；将其状态重置为暂停状态，将其版本号改为当前流程的版本号；
        rdaWfNode = new RdaWfNode();
        rdaWfNode.setWorkflowid(workflowid);
        rdaWfNode.setStateid(WorkflowStateid.wfNodeActiveid.intValue());
        List<RdaWfNode> ActiveNodes = rdaWfNodeService.selectRdaWfNodeList(rdaWfNode);//根据流程id查询所有活动状态的节点
        for (RdaWfNode rdaWfNode2 : ActiveNodes) {
            Long nodeId = rdaWfNode2.getId();
            AffectedNodeids += "|"+nodeId;
            rdaWfNode2 = new RdaWfNode();
            rdaWfNode2.setId(nodeId);
            rdaWfNode2.setStateid(WorkflowStateid.wfNodeSuspendid.intValue());
            rdaWfNodeService.updateRdaWfNode(rdaWfNode2);

            rdaWfNode = new RdaWfNode();
            rdaWfNode.setId(nodeId);
            rdaWfNode.setRevision("" + revisionNumber);
            rdaWfNodeService.updateRdaWfNode(rdaWfNode);
        }
        //c 查询该流程所有创建状态的节点；将所有创建状态的节点的版本号改为当前流程的版本号；
        rdaWfNode = new RdaWfNode();
        rdaWfNode.setWorkflowid(workflowid);
        rdaWfNode.setStateid(WorkflowStateid.wfNodeCreateid.intValue());
        List<RdaWfNode> CreateNodes = rdaWfNodeService.selectRdaWfNodeList(rdaWfNode);//根据流程id查询所有创建状态的节点
        for (RdaWfNode rdaWfNode3 : CreateNodes) {
            Long nodeId = rdaWfNode3.getId();
            rdaWfNode = new RdaWfNode();
            rdaWfNode.setId(nodeId);
            rdaWfNode.setRevision("" + revisionNumber);
            rdaWfNodeService.updateRdaWfNode(rdaWfNode);
        }

        //获得拒绝的目标节点
        String rejectId = "";
        String rejectscript = "";
        //如果被拒绝到开始节点：
        if(refuseType.equalsIgnoreCase("Reject_tostart")){
            //查询开始节点
            RdaWfNode startNode=rdaWfNodeService.selectRdaWfNodeStartOrEnd(workflowid,0l);//开始节点
            rejectId=startNode.getId().toString();
            //查询当前节点的拒绝到开始的脚本；
             rdaWfNode=new RdaWfNode();
             rdaWfNode=rdaWfNodeService.selectRdaWfNodebyById(nodeid);
            rejectscript=rdaWfNode.getRejecttostartScript();
        }else {//拒绝到指定节点
            //拒绝到指定节点
            String id[] = refuseType.split("_");
            rejectId = id[1];
            String relid=id[2];
            //从拒绝路径中得到拒绝脚本
            RdaWorkflow2NodeRel rdaWorkflow2NodeRel=rdaWorkflow2NodeRelService.selectRdaWorkflow2NodeRelById(Long.valueOf(relid));
            rejectscript=rdaWorkflow2NodeRel.getRejectScript();
        }
        if(rejectscript!=null && rejectscript.length()>0){
            appovedScript(rejectscript,workflowid);
        }
        //创建拒绝路径,返回关系relId,建立当前节点与上一节点的拒绝路径，影响节点属性（affected_Nodeid）上收集的活动节点(ActiveNodes)的id，多个用|竖线隔开，，操作状态改为已完成，操作时间写为当前时间；
        RdaWorkflow2NodeRel rdaWorkflow2NodeRel = new RdaWorkflow2NodeRel();
        Long relId=SnowFlakeUtils.nextId();
        rdaWorkflow2NodeRel.setId(relId);
        rdaWorkflow2NodeRel.setFromid(nodeid);
        rdaWorkflow2NodeRel.setToid(Long.valueOf(rejectId));
        rdaWorkflow2NodeRel.setWorkflowid(workflowid);
        rdaWorkflow2NodeRel.setOperationType("Reject");
        rdaWorkflow2NodeRel.setRejectScript(rejectscript);
        rdaWorkflow2NodeRel.setOperationState(1L);
        rdaWorkflow2NodeRel.setOperationTime(DateUtils.getNowDate());
        rdaWorkflow2NodeRel.setAffectedNodeids(AffectedNodeids);//影响节点id
        rdaWorkflow2NodeRelService.insertRdaWorkflow2NodeRel(rdaWorkflow2NodeRel);

        //设置目标节点状态为创建状态
        rdaWfNode = new RdaWfNode();
        rdaWfNode.setId(Long.valueOf(rejectId));
        rdaWfNode.setStateid(WorkflowStateid.wfNodeCreateid.intValue());
        // 2022-01-15 重置完成时间 start
        rdaWfNode.setAccomplishTime(null);
        rdaWfNode.setCostTimeDay(null);
        rdaWfNodeService.updateRdaWfNodeByStartTime(rdaWfNode);

        //2.5 修改目标节点Rejectskipcomplete的属性值为True，
        rdaWfNodeService.updateRdaWfNodeByRejectskipcomplete(Long.valueOf(rejectId), true);

        //填写拒绝路径的relId到Rejectfromid属性；修改目标节点版本号为当前流程的版本号

        rdaWfNode = new RdaWfNode();
        rdaWfNode.setId(Long.valueOf(rejectId));
        rdaWfNode.setRevision("" + revisionNumber);
        rdaWfNode.setRejectfromid(relId.toString());
        rdaWfNodeService.updateRdaWfNode(rdaWfNode);

        //启动该目标节点（调用节点启动函数）；
        workflowStartUpNode(Long.valueOf(rejectId), workflowid);
        return toAjax(1);
    }

    /**
     * 流程拒绝：原有逻辑，重走已完成节点
     */
    public AjaxResult myWFTaskAppoveRefuse(Long ids,String approveExplain,String refuseType,RdaWfTask task){

        //1.设置当前任务为完成状态，并将任务的操作类型设置为拒绝 start
        RdaWfTask rdaWfTask=new RdaWfTask();
        rdaWfTask.setId(ids);
        rdaWfTask.setStateid(WorkflowStateid.wfTaskCompleteid);
        rdaWfTask.setAccomplishTime(DateUtils.getNowDate());
        rdaWfTask.setApproveExplain(approveExplain);
        rdaWfTask.setOperId("拒绝");
        rdaWfTaskService.updateRdaWfTask(rdaWfTask);// update rda_wf_task set Stateid=#{} where id=#{}
        //1.设置当前节点任务为完成状态 end

        //2.查询该任务Task关联的节点及节点信息(UserAndOr)
        // 根据当前任务id查询当前nodeid
        RdaWfTask rdaWfTask2=rdaWfTaskService.selectRdaWfTaskByid(ids);// rda_wf_task where id=#{id}
        Long nodeid=rdaWfTask2.getNodeid();

        //通过nodeid得到当前节点信息
        RdaWfNode rdaWfNode=rdaWfNodeService.selectRdaWfNodebyInfo(nodeid);// rda_wf_node where id=#{nodeid}

        //获取流程id
        Long workflowid=rdaWfTask2.getWorkflowid();//流程id

        //3.1 将当前节点设置为完成、并将节点响应类型设置为拒绝
        nodeRefuse(nodeid,workflowid,task);

        //4 修改流程版本，版本号加1
        RdaWorkflow rdaWorkflow=new RdaWorkflow();
        RdaWorkflow rdaWorkflow2=rdaWorkflowService.selectRdaWorkflowById(workflowid);
        String revision=rdaWorkflow2.getRevision();//获取当前版本号
        if(revision==null){
            revision="0";
        }
        Integer VersionNumber=Integer.parseInt(revision);
        Integer revisionNumber=VersionNumber+1;
        rdaWorkflow.setId(rdaWorkflow2.getId());
        rdaWorkflow.setRevision(""+revisionNumber);
        rdaWorkflowService.updateRdaWorkflow(rdaWorkflow);

        //5 如果被拒绝到开始节点：
        if(refuseType.equalsIgnoreCase("Reject_tostart")){
            //5.1 查询该流程所有活动状态的任务;将所有活动状态的任务的状态修改为作废状态
            RdaWfTask rdaWfTask3=new RdaWfTask();
            rdaWfTask3.setStateid(WorkflowStateid.wfTaskActiveid);//nodeStateActiveid
            rdaWfTask3.setWorkflowid(workflowid);
            rdaWfTask3.setToolbarType("1");
            List<RdaWfTask> rdaWfTaskList=rdaWfTaskService.selectRdaWfTaskList(rdaWfTask3);//rda_wf_task where workflowid=#{workflowid} and Stateid=#{Stateid}
            for(RdaWfTask rdaWfTask4:rdaWfTaskList){
                RdaWfTask rdaWfTask5=new RdaWfTask();
                rdaWfTask5.setId(rdaWfTask4.getId());
                rdaWfTask5.setStateid(WorkflowStateid.wfTaskObsoletedid);
                rdaWfTaskService.updateRdaWfTask(rdaWfTask5);
            }
            //5.2 查询该流程所有活动状态的节点；将其状态重置为创建状态；
            RdaWfNode rdaWfNode3=new RdaWfNode();
            rdaWfNode3.setWorkflowid(workflowid);
            rdaWfNode3.setStateid(WorkflowStateid.wfNodeActiveid.intValue());
            List<RdaWfNode> rdaWfNodeActivityList=rdaWfNodeService.selectRdaWfNodeList(rdaWfNode3);//rda_wf_node where Workflowid=#{Workflowid} and Stateid=#{Stateid}
            for(RdaWfNode rdaWfNodeActivity: rdaWfNodeActivityList){
                rdaWfNode3=new RdaWfNode();
                rdaWfNode3.setId(rdaWfNodeActivity.getId());
                rdaWfNode3.setStateid(WorkflowStateid.wfNodeCreateid.intValue());
                rdaWfNodeService.updateRdaWfNode(rdaWfNode3);
            }


            //5.3 查询该流程所有完成状态的节点；将其状态重置为创建状态；
            rdaWfNode3=new RdaWfNode();
            rdaWfNode3.setWorkflowid(workflowid);
            rdaWfNode3.setStateid(WorkflowStateid.wfNodeCompleteid.intValue());
            List<RdaWfNode> rdaWfNodeCompleteList=rdaWfNodeService.selectRdaWfNodeList(rdaWfNode3);//rda_wf_node where Workflowid=#{Workflowid} and Stateid=#{Stateid}
            for (RdaWfNode rdaWfNodeComplete: rdaWfNodeCompleteList){
                rdaWfNode3=new RdaWfNode();
                rdaWfNode3.setId(rdaWfNodeComplete.getId());
                rdaWfNode3.setStateid(WorkflowStateid.wfNodeCreateid.intValue());
                // 2022-01-15 重置完成时间 start
                rdaWfNode3.setAccomplishTime(null);
                rdaWfNode3.setCostTimeDay(null);
                rdaWfNodeService.updateRdaWfNodeByStartTime(rdaWfNode3);
            }

            //5.4 查询该流程所有创建状态的节点；将所有创建状态的节点的版本号改为当前流程的版本号
            rdaWfNode3=new RdaWfNode();
            rdaWfNode3.setWorkflowid(workflowid);
            rdaWfNode3.setStateid(WorkflowStateid.wfNodeCreateid.intValue());
            List<RdaWfNode> rdaWfNodeCreateStatusList=rdaWfNodeService.selectRdaWfNodeList(rdaWfNode3);// rda_wf_node where Workflowid=#{Workflowid} and Stateid=#{Stateid}
            for(RdaWfNode rdaWfNodeCreateStatus:rdaWfNodeCreateStatusList){
                rdaWfNode3=new RdaWfNode();
                rdaWfNode3.setId(rdaWfNodeCreateStatus.getId());
                rdaWfNode3.setRevision(""+revisionNumber);
                rdaWfNodeService.updateRdaWfNode(rdaWfNode3);
            }

            //获取当前节点拒绝到开始节点脚本，执行降级操作
            String error=refuseGoToTargetStart(rdaWfNode);
            if(error!="" && !"".equals(error)){
                return error("wf1002:流程相关对象降级失败");
            }

            // 2022-01-10将开始节点设置为活动状态并为开始节点创建任务
            RdaWfNode startNode=rdaWfNodeService.selectRdaWfNodeStartOrEnd(workflowid,0l);//开始节点
            workflowStartUpNode(startNode.getId(),workflowid);

            //5.7 建立当前节点与开始节点的拒绝路径（操作时间写为当前时间）；
            RdaWorkflow2NodeRel rdaWorkflow2NodeRel=new RdaWorkflow2NodeRel();
            rdaWorkflow2NodeRel.setId(SnowFlakeUtils.nextId());
            rdaWorkflow2NodeRel.setFromid(nodeid);
            rdaWorkflow2NodeRel.setToid(startNode.getId());
            rdaWorkflow2NodeRel.setWorkflowid(workflowid);
            rdaWorkflow2NodeRel.setOperationType("Reject");
            rdaWorkflow2NodeRel.setOperationState(1L);
            rdaWorkflow2NodeRel.setOperationTime(DateUtils.getNowDate());
            rdaWorkflow2NodeRelService.insertRdaWorkflow2NodeRel(rdaWorkflow2NodeRel);

        }else if(refuseType.equalsIgnoreCase("reject_toprevious")){
        }else{
            //拒绝到指定节点
            String id[]=refuseType.split("_");
            String rejectId=id[1];
            //关系表关系id
            String relId=id[2];
            RdaWfNode rdaWfNode2=rdaWfNodeService.selectRdaWfNodebyById(Long.valueOf(rejectId));
            if(rdaWfNode2==null){
                return AjaxResult.error("wf2001：节点不存在");
            }else{
                //根据fromid查询所有下级  查询指定节点之后的所有的下层节点（多层递归查询），
                List<RdaWorkflow2NodeRel> nextList=rdaWorkflow2NodeRelService.selectRdaWorkflow2NodeRelSubordinate(Long.valueOf(rejectId),"Approve");
                for(RdaWorkflow2NodeRel rdaWorkflow2NodeRel2:nextList){
                    //  查询该下层节点所关联的活动任务（该节点关联的活动状态的Task），并将其设置为作废状态
                    List<RdaWfTask> rdaWfTaskList=rdaWfTaskService.selectRdaWfTaskByNodeid(rdaWorkflow2NodeRel2.getToid(),workflowid);
                    for(RdaWfTask rdaWfTask3:rdaWfTaskList){
                        if(rdaWfTask3.getStateid().equals(WorkflowStateid.wfTaskActiveid)){
                            RdaWfTask rdaWfTask4=new RdaWfTask();
                            rdaWfTask4.setId(rdaWfTask3.getId());
                            rdaWfTask4.setStateid(WorkflowStateid.wfTaskObsoletedid);
                            rdaWfTaskService.updateRdaWfTask(rdaWfTask4);
                        }
                    }

                    //将该下层节点的状态重置为创建；
                    rdaWfNode = new RdaWfNode();
                    rdaWfNode.setId(rdaWorkflow2NodeRel2.getToid());
                    rdaWfNode.setStateid(WorkflowStateid.wfNodeCreateid.intValue());
                    // 2021-01-15 重置完成时间 start
                    rdaWfNode.setAccomplishTime(null);
                    rdaWfNode.setCostTimeDay(null);
                    rdaWfNodeService.updateRdaWfNodeByStartTime(rdaWfNode);
                    // 2021-01-15 重置完成时间 start
                    // 将该下层节点的版本号改为当前流程的版本号；
                    rdaWfNode=new RdaWfNode();
                    rdaWfNode.setId(rdaWorkflow2NodeRel2.getToid());
                    rdaWfNode.setRevision(""+revisionNumber);
                    rdaWfNodeService.updateRdaWfNode(rdaWfNode);
                }
                //启动该指定节点（调用节点启动函数）；
                workflowStartUpNode(Long.valueOf(rejectId),workflowid);
                //建立当前节点与上一节点的拒绝路径（操作时间写为当前时间）rda_workflow2_node_rel
                RdaWorkflow2NodeRel rdaWorkflow2NodeRel=new RdaWorkflow2NodeRel();
                rdaWorkflow2NodeRel.setId(SnowFlakeUtils.nextId());
                rdaWorkflow2NodeRel.setFromid(nodeid);
                rdaWorkflow2NodeRel.setToid(Long.valueOf(rejectId));
                rdaWorkflow2NodeRel.setWorkflowid(workflowid);
                rdaWorkflow2NodeRel.setOperationType("Reject");
                rdaWorkflow2NodeRel.setOperationState(1L);
                rdaWorkflow2NodeRel.setOperationTime(DateUtils.getNowDate());
                rdaWorkflow2NodeRelService.insertRdaWorkflow2NodeRel(rdaWorkflow2NodeRel);

                //获取当前节点拒绝到开始节点脚本，执行降级操作
                //得到当前拒绝路径
//                rdaWorkflow2NodeRelService.selectRdaWorkflow2NodeRelList(Long.valueOf(rejectId),workflowid,"Reject");
                RdaWorkflow2NodeRel rdaWorkflow2NodeRel2=rdaWorkflow2NodeRelService.selectRdaWorkflow2NodeRelById(Long.valueOf(relId));
                Long toid=rdaWorkflow2NodeRel2.getToid();
                if(rdaWorkflow2NodeRel2.getRejectScript()!=null && rdaWorkflow2NodeRel2.getRejectScript().length()>0){
                    appovedScript(rdaWorkflow2NodeRel2.getRejectScript(),workflowid);
                }
                rdaWfNode = new RdaWfNode();
                rdaWfNode.setWorkflowid(workflowid);
                rdaWfNode.setId(toid);
                List<RdaWfNode> rdaWfNodeList=rdaWfNodeService.selectRdaWfNodeList(rdaWfNode);
                rdaWfNode = new RdaWfNode();
                rdaWfNode=rdaWfNodeList.get(0);
                String error=refuseGoToTargetStart(rdaWfNode);
                if(error!="" && !"".equals(error)){
                    return error("wf1002:流程相关对象降级失败");
                }
            }

        }

        return toAjax(1);
    }

    /**
     * 流程同意
     */
    public AjaxResult myWFTaskAppoveAgree(Long ids,String approveExplain,RdaWfTask workflowTask){
        //1.设置当前节点任务为完成状态 start
        RdaWfTask rdaWfTask=new RdaWfTask();
        rdaWfTask.setId(ids);
        rdaWfTask.setStateid(WorkflowStateid.wfTaskCompleteid);
        rdaWfTask.setAccomplishTime(DateUtils.getNowDate());
        rdaWfTask.setApproveExplain(approveExplain);
        rdaWfTask.setCostTimeDay("1");
        rdaWfTask.setOperId("同意");
        rdaWfTaskService.updateRdaWfTask(rdaWfTask);// update rda_wf_task set Stateid=#{} where id=#{}
        //1.设置当前节点任务为完成状态 end

        //2.查询该任务Task关联的节点及节点信息(UserAndOr)
        // 根据当前任务id查询当前nodeid
        RdaWfTask rdaWfTask2=rdaWfTaskService.selectRdaWfTaskByid(ids);// rda_wf_task where id=#{id}
        Long nodeid=rdaWfTask2.getNodeid();

        //2022-02-10 根据流程id、节点id查询获取代理类型 start
        RdaWfTask task=new RdaWfTask();
        task.setWorkflowid(rdaWfTask2.getWorkflowid());
        task.setNodeid(nodeid);
        List<RdaWfTask> wftaskList=rdaWfTaskService.selectRdaWfTaskList(task);
        for(RdaWfTask wfTask:wftaskList){
            if("抄送".equals(wfTask.getAgentTypeid())){
                //将被委托人任务设置为完成
                rdaWfTask=new RdaWfTask();
                rdaWfTask.setId(wfTask.getId());
                rdaWfTask.setStateid(WorkflowStateid.wfTaskCompleteid);
                rdaWfTask.setAccomplishTime(DateUtils.getNowDate());
                rdaWfTask.setApproveExplain(approveExplain);
                rdaWfTask.setCostTimeDay("1");
                rdaWfTask.setOperId("同意");
                rdaWfTaskService.updateRdaWfTask(rdaWfTask);
            }else if("同时处理".equals(wfTask.getAgentTypeid())){
                //状态为同时处理时，将非完成状态设置为作废状态
                rdaWfTask=new RdaWfTask();
                if(!wfTask.getStateid().equals(WorkflowStateid.wfTaskCompleteid)){
                    rdaWfTask.setId(wfTask.getId());
                    rdaWfTask.setStateid(WorkflowStateid.wfTaskObsoletedid);
                    rdaWfTaskService.updateRdaWfTask(rdaWfTask);
                }
            }
        }
        //2022-02-10 根据流程id、节点id查询 end

        //通过nodeid得到当前节点信息
        RdaWfNode rdaWfNode=rdaWfNodeService.selectRdaWfNodebyInfo(nodeid);// rda_wf_node where id=#{nodeid}

        //获取当前节点拒绝路径id
        String rejectfromid=rdaWfNode.getRejectfromid();

        //拒绝后跳过已完成节点
        boolean isRejectSkipComplete=rdaWfNode.isRejectSkipComplete();
        //获取流程id
        Long workflowid=rdaWfTask2.getWorkflowid();//流程id


        //查询结束节点
        RdaWfNode nodeEnd=rdaWfNodeService.selectRdaWfNodeStartOrEnd(workflowid,-1L);
        Long nodeIdEnd=nodeEnd.getId();

        //3.处理该节点：（当前节点） start
        // 查询当前节点（当前任务Task关联的节点）所关联的所有Task；
        RdaWfTask rdaWfTaskNodeid=new RdaWfTask();
        rdaWfTaskNodeid.setNodeid(rdaWfTask2.getNodeid());
        List<RdaWfTask> taskList= rdaWfTaskService.selectRdaWfTaskList(rdaWfTaskNodeid);

        //3.1 如果该节点所关联的Task数量为1)，则直接完成该节点即设置该节点为完成状态； start
        if(taskList.size()==1){
//            rdaWfNodeService.updateRdaWfNodeByToStateid(nodeid, nodeStateAppoveid);
            rdaWfNodeService.updateRdaWfNodeByToStateid(nodeid, WorkflowStateid.wfNodeCompleteid,"批准");
        }

        //3.2 如果该节点所关联的Task数量为1（即只有当前的一个任务），则直接完成该节点即设置该节点为完成状态；start
        //List<RdaWorkflow2NodeRel> rdaWorkflow2NodeRel=rdaWorkflow2NodeRelService.selectRdaWorkflow2NodeRelByToid(rdaWfNode.getId(),workflowid); // from rda_workflow2_node_rel where toid=#{toid} and workflowid=#{workflowid}
        //if(rdaWorkflow2NodeRel.size()==1){//当前上级只有一个的时候则设置当前节点为完成状态
        //    rdaWfNodeService.updateRdaWfNodeByToStateid(nodeId, nodeStateAppoveid);
        //}
        //3.2如果该节点所关联的Task数量为1（即只有当前的一个任务），则直接完成该节点即设置该节点为完成状态；end

        //3.2如果该节点所关联的Task数量大于1 start
        boolean NodeCheck=true;
        boolean WorkFlowCheck=true;
        Integer nextnodesize=0;
        if(taskList.size()>1 ){
            //3.3.1 如果节点的UserAndOr属性为Or，则设置当前节点为完成状态，并将该节点关联的其它Task中未完成的Task设置为作废状态； start
            if(rdaWfNode.getUserandor().equals("or")){
                for (RdaWfTask tmprdaWfTask:taskList) {
                    Long taskid=tmprdaWfTask.getId();
                    if(!taskid.equals(ids)){
                        RdaWfTask rdaWfTask3=new RdaWfTask();
                        rdaWfTask3.setId(taskid);
                        List<RdaWfTask> stateidList=rdaWfTaskService.selectRdaWfTaskList(rdaWfTask3);//rda_wf_task where id=#{taskid}
                        Long stateid=stateidList.get(0).getStateid();
//                        if(!stateid.equals(taskStateAppoveid)){
                        if(!stateid.equals(WorkflowStateid.wfTaskCompleteid)){
                            rdaWfTask.setId(taskid);
//                            rdaWfTask.setStateid(taskStateCancelid);
                            rdaWfTask.setStateid(WorkflowStateid.wfTaskObsoletedid);
                            rdaWfTaskService.updateRdaWfTask(rdaWfTask);
                        }
                    }
                }
            }
            //3.3.1 如果节点的UserAndOr属性为Or，则设置该节点为完成状态，并将该节点关联的其它Task中未完成的Task设置为作废状态； end

            //3.3.2 如果节点的UserAndOr属性为And，则判断该节点关联的其它Task是否有未完成的Task start
            if(rdaWfNode.getUserandor().equals("and")){
                boolean tmpCheck=true;
                for(RdaWfTask tmprdaWfTask:taskList)  {
                    Long taskid=tmprdaWfTask.getId();
                    RdaWfTask RdaWfTask=new RdaWfTask();
                    RdaWfTask.setId(taskid);
                    List<RdaWfTask> stateidList=rdaWfTaskService.selectRdaWfTaskList(RdaWfTask);//rda_wf_task(节点表) where id=#{taskid}
                    Long stateid=stateidList.get(0).getStateid();
//                    if(!stateid.equals(taskStateAppoveid) && !taskid.equals(ids)){
//                    if(!stateid.equals(WorkflowStateid.wfTaskCompleteid) && !taskid.equals(ids)){
                    //2022-01-10 状态更改为创建或活动状态
                    if((stateid.equals(WorkflowStateid.wfTaskCreateid) || stateid.equals(WorkflowStateid.wfTaskActiveid)) && !taskid.equals(ids)){
                        tmpCheck=false;
                        NodeCheck=false;
                        break;
                    }
                }

                if(tmpCheck){
//                    rdaWfNodeService.updateRdaWfNodeByToStateid(nodeid, nodeStateAppoveid);
                    rdaWfNodeService.updateRdaWfNodeByToStateid(nodeid, WorkflowStateid.wfNodeCompleteid,"批准");
                    //NodeCheck=true;
                }
                //如果节点是and检查该节点关联的其他的task,如果状态都是完成则完成该节点,如果有一个task未完成结束程序（不用做任何操作）end
            }
            //3.3.2 如果节点的UserAndOr属性为And，则判断该节点关联的其它Task是否有未完成的Task end
        }

        //4 如果该节点被完成（NodeCheck=True），则查询该节点的下一节点(可能有多个)及相关属性 start
        if(NodeCheck) {
            //4 如果其他Task都已经完成则设置该节点为完成状态 start
//            rdaWfNodeService.updateRdaWfNodeByToStateid(nodeid, nodeStateAppoveid);//3.3.2.2 跟3.3.1 是同一操作
            rdaWfNodeService.updateRdaWfNodeByToStateid(nodeid, WorkflowStateid.wfNodeCompleteid, "批准");//3.3.2.2 跟3.3.1 是同一操作

            //原有逻辑，重走所有节点，Word中第5条
            if (isRejectSkipComplete == false) {
                //查询当前节点的下一节点
                List<RdaWorkflow2NodeRel> rdaWorkflow2NodeRel2 = rdaWorkflow2NodeRelService.selectRdaWorkflow2NodeRelByFromid(nodeid, workflowid, "Approve");//根据当前节点查询该节点下一节点  rda_workflow2_node_rel where fromid=#{fromid}
                //得到下一节点集合进行处理（分支处理）2022-03-01 start
                ArrayList<RdaWorkflow2NodeRel> nodeRelList=workflowBranch(rdaWorkflow2NodeRel2,workflowTask.getApprove());
                if(nodeRelList!=null && nodeRelList.size()!=0){
                    rdaWorkflow2NodeRel2=nodeRelList;
                }
                //得到下一节点集合进行处理（分支处理）2022-03-01 end
                nextnodesize = rdaWorkflow2NodeRel2.size();
                //5.循环处理下一节点（NextNode） start
                ArrayList<Long> NextNodeList=new ArrayList<Long>();
                for (RdaWorkflow2NodeRel rdaWorkflow2NodeRel3 : rdaWorkflow2NodeRel2) {
                    //循环得到下一节点nextnode的id及相关信息
                    Long NextNode = rdaWorkflow2NodeRel3.getToid();
                    RdaWfNode rdaWfNextNode = rdaWfNodeService.selectRdaWfNodebyInfo(NextNode);// rda_wf_node where id=#{nodeid}

                    //2022-05-07 流程节点条件校验start
                    NextNodeList.add(NextNode);
                    boolean check= condition(rdaWfNextNode);
                    if(check){
                        for(Long NextNodeid:NextNodeList){
                            rdaWfNode=new RdaWfNode();
                            rdaWfNode.setId(NextNodeid);
                            rdaWfNode.setStateid(WorkflowStateid.wfNodeObsoleteid.intValue());
                            rdaWfNodeService.updateRdaWfNode(rdaWfNode);
                            rdaWfTaskService.deleteRdaWfTaskByNodeidWorkflowid(NextNodeid,rdaWfNextNode.getWorkflowid());
                            if(NextNode.equals(NextNodeid)){
                                workflowStartUpNode(NextNode, workflowid);
                            }
                        }
                        break;
                    }
                    //2022-05-07 流程节点条件校验end

                    //查询下一节点的所关联的前置节点；
                    List<RdaWorkflow2NodeRel> rdaWorkflow2NodeRel4 = rdaWorkflow2NodeRelService.selectRdaWorkflow2NodeRelByToid(NextNode, workflowid, "Approve");//查询前置节点 rda_workflow2_node_rel where toid=#{toid}
                    WorkFlowCheck = false;
                    //5.1 查询下一节点的所关联的前置节点；（变量WorkFlowCheck为false）；end

                    //5.2 如果前置节点数量为1(该下一节点只有当前节点一个前置节点) start
                    if (rdaWorkflow2NodeRel4.size() == 1) {
                        // 5.2.1 如果NextNode不是结束节点，则直接启动该下一节点（调节点启动函数）；
                        if (!NextNode.equals(nodeIdEnd)) {
                            workflowStartUpNode(NextNode, workflowid);
                            //自动节点处理
                            boolean automaticCheck = automaticNodeMethod(NextNode, workflowid, approveExplain);
                            if(automaticCheck){
                                break;
                            }

                        }

                        //5.2.2 如果NextNode是结束节点，则需要完成该流程
                        if (NextNode.equals(nodeIdEnd)) {
                            WorkFlowCheck = true;
                        }
                    }
                    //5.2 如果前置节点数量为1(该下一节点只有当前节点一个前置节点) end

                    // 5.3如果前置节点数量>1，而且该NextNode节点的NodeAndOr属性为Or start
                    if (rdaWorkflow2NodeRel4.size() > 1 && rdaWfNode.getNodeandor().equals("or")) {
                        //5.3.1 则将其他未完成的前置节点和前置节点未完成的Task设置为作废状态； start
                        for (RdaWorkflow2NodeRel rdaWorkflow2NodeRel5 : rdaWorkflow2NodeRel4) {
                            Long fromId = rdaWorkflow2NodeRel5.getFromid();
                            RdaWfNode rdaWfNode3 = rdaWfNodeService.selectRdaWfNodebyInfo(fromId);// from rda_wf_node where id=#{fromId}
//                        if(!rdaWfNode3.getStateid().equals(nodeStateAppoveid) && !nodeid.equals(fromId)){
                            if (!rdaWfNode3.getStateid().equals(WorkflowStateid.wfNodeCompleteid.intValue()) && !nodeid.equals(fromId)) {
                                rdaWfNodeService.updateRdaWfNodeStateid(rdaWfNode3.getId(), WorkflowStateid.wfNodeObsoleteid);
                                //更新节点的未完成任务未作废
                                RdaWfTask rdaWfTaskNodeid2 = new RdaWfTask();
                                rdaWfTaskNodeid2.setNodeid(fromId);
                                List<RdaWfTask> taskList2 = rdaWfTaskService.selectRdaWfTaskList(rdaWfTaskNodeid2);
                                for (RdaWfTask tmprdaWfTask3 : taskList2) {
                                    Long taskid2 = tmprdaWfTask3.getId();
                                    RdaWfTask rdaWfTask3 = new RdaWfTask();
                                    rdaWfTask3.setId(taskid2);
                                    List<RdaWfTask> stateidList3 = rdaWfTaskService.selectRdaWfTaskList(rdaWfTask3);//rda_wf_task where id=#{taskid}
                                    Long stateid = stateidList3.get(0).getStateid();
//                                if(!stateid.equals(taskStateAppoveid) ){
                                    if (!stateid.equals(WorkflowStateid.wfTaskCompleteid)) {
                                        rdaWfTask.setId(taskid2);
//                                    rdaWfTask.setStateid(taskStateCancelid);
                                        rdaWfTask.setStateid(WorkflowStateid.wfTaskObsoletedid);
                                        rdaWfTaskService.updateRdaWfTask(rdaWfTask);
                                    }
                                }
                            }

                        }
                        //5.3.1 则将其他未完成的前置节点和前置节点未完成的Task设置为作废状态； end

                        //5.3.2 如果NextNode不是结束节点，则直接启动该下一节点（调节点启动函数）；start
                        if (!NextNode.equals(nodeIdEnd)) {
                            workflowStartUpNode(NextNode, workflowid);
                        }

                        //5.3.3 如果NextNode是结束节点，则需要完成该流程 start
                        if (NextNode.equals(nodeIdEnd)) {
                            WorkFlowCheck = true;
                        }
                    }
                    // 5.3如果前置节点数量>1，而且该NextNode节点的NodeAndOr属性为Or end

                    //5.4 如果前置节点数量>1，而且该NextNode节点的NodeAndOr属性为And，则判断该NextNode节点关联的其它前置节点是否有未完成前置Node start
                    boolean tmpCheck2 = true;
                    if (rdaWorkflow2NodeRel4.size() > 1 && rdaWfNode.getNodeandor().equals("and")) {
                        for (RdaWorkflow2NodeRel rdaWorkflow2NodeRel5 : rdaWorkflow2NodeRel4) {
                            Long fromId = rdaWorkflow2NodeRel5.getFromid();
                            RdaWfNode rdaWfNode3 = rdaWfNodeService.selectRdaWfNodebyById(fromId);// from rda_wf_node where id=#{fromId}
                            Integer Stateid = rdaWfNode3.getStateid();
                            Long Stateid2 = Stateid.longValue();
//                        if (!Stateid2.equals(nodeStateAppoveid)) {
//                            if (Stateid2.equals(WorkflowStateid.wfNodeActiveid)) {
                            //2020-01-10新增创建状态判断
                            if (Stateid2.equals(WorkflowStateid.wfNodeActiveid) || Stateid2.equals(WorkflowStateid.wfNodeCreateid)) {
                                tmpCheck2 = false;
                                break;
                            }
                            //5.4.1 如有未完成，则直接结束该操作（只完成Node不启动下一节点）； start
                        }
                        //5.4.2 如都已经完成，则判断NextNode是不是结束节点 start
                        if (tmpCheck2) {

                            //5.4.1 如果NextNode不是结束节点，则直接启动该下一节点（调节点启动函数）；start
                            if (!NextNode.equals(nodeIdEnd)) {
                                workflowStartUpNode(NextNode, workflowid);
                            }

                            //5.4.2 如果NextNode是结束节点，则需要完成该流程 start
                            if (NextNode.equals(nodeIdEnd)) {
                                WorkFlowCheck = true;
                            }

//                        5.5 如果该节点被启动，则判断该节点是否为自动节点，如果为自动节点（写成自动节点完成函数）：
                            automaticNodeMethod(NextNode, workflowid, approveExplain);
                        }
                        //5.4.2 如都已经完成，则判断NextNode是不是结束节点 end
                    }
                    //5.4 如果前置节点数量>1，而且该NextNode节点的NodeAndOr属性为And，则判断该NextNode节点关联的其它前置节点是否有未完成前置Node end
                }
            }
            //跳过已完成节点，按照Word逻辑第6条重写
            if(isRejectSkipComplete)
            {
                //得到节点Rejectfromid属性，查询拒绝路径得到affected_Nodeid属性上属性值：活动节点(ActiveNodes)的id
                //6.1 获取Rejectfromid属性值，从流程节点关系表中获取该id的拒绝路径，如有有错则报错并终止程序，已执行程序回滚；（根据当前节点查询当前节点拒绝路径）

                //根据流程id查询暂停状态节点，并且将暂停节点重设为活动状态
                rdaWfNode=new RdaWfNode();
                rdaWfNode.setWorkflowid(workflowid);
                rdaWfNode.setStateid(WorkflowStateid.wfNodeSuspendid.intValue());
                List<RdaWfNode> rdaWfNodeList=rdaWfNodeService.selectRdaWfNodeList(rdaWfNode);
                for(RdaWfNode wfNode:rdaWfNodeList){
                    rdaWfNode=new RdaWfNode();
                    rdaWfNode.setId(wfNode.getId());
                    rdaWfNode.setStateid(WorkflowStateid.wfNodeActiveid.intValue());
                    rdaWfNodeService.updateRdaWfNode(rdaWfNode);
                }
                //根据流程id查询暂停状态的任务，将暂停状态的任务设置为活动状态
                rdaWfTask=new RdaWfTask();
                rdaWfTask.setWorkflowid(workflowid);
                rdaWfTask.setStateid(WorkflowStateid.wfTaskSuspendid);
                rdaWfTask.setToolbarType("1");
                List<RdaWfTask> rdaWfTaskList=rdaWfTaskService.selectRdaWfTaskList(rdaWfTask);
                for(RdaWfTask wfTask:rdaWfTaskList){
                    rdaWfTask=new RdaWfTask();
                    rdaWfTask.setId(wfTask.getId());
                    rdaWfTask.setStateid(WorkflowStateid.wfTaskActiveid);
                    rdaWfTaskService.updateRdaWfTaskAll(rdaWfTask);
                }
                rdaWfNodeService.updateRdaWfNodeByRejectskipcomplete(nodeid,false);

                //获取当前节点的拒绝路径，根据当前节点拒绝路径查询关系表，通过关系表获取执行脚本
                if(rejectfromid!=null && !"".equals(rejectfromid) ) {
                    Long id = Long.parseLong(rejectfromid);
                    RdaWorkflow2NodeRel rdaWorkflow2NodeRel = rdaWorkflow2NodeRelService.selectRdaWorkflow2NodeRelById(id);
                    String rejectScript = rdaWorkflow2NodeRel.getRejectScript();//获取节点脚本
                    if (rejectScript != null && !"".equals(rejectScript)) {
                        String moduleName = "";
                        String operation = "";
                        String startStateName = "";
                        String[] appovedScriptTmp1 = rejectScript.split(":");
                        String[] moduleNames = appovedScriptTmp1[0].split("_");
                        String EndstateName = appovedScriptTmp1[1];
                        if (moduleNames.length >= 3) {
                            moduleName = moduleNames[0];
                            operation = moduleNames[1];
                            int index = appovedScriptTmp1[0].indexOf("_");
                            index = rejectScript.indexOf("_", index + 1);
                            startStateName = appovedScriptTmp1[0].substring(index).substring(1);
                        }
                        //生命周期反向升级
                        //document_demote_Frozen:Private
                        //document_promote_Private_Frozen
                        if (operation.equalsIgnoreCase("demote")) {
                            operation = "promote";
                            EndstateName=startStateName;
                            RdaWorkflowObjectRel rdaWorkflowObjectRel =new RdaWorkflowObjectRel();
                            rdaWorkflowObjectRel.setWorkflowid(workflowid);
                            rdaWorkflowObjectRel.setPurpose("approve");
                            rdaWorkflowObjectRel.setObjectModuleName(moduleName);
                            List<RdaWorkflowObjectRel> list=rdaWorkflowObjectRelService.selectRdaWorkflowObjectRelList(rdaWorkflowObjectRel);
                            for(RdaWorkflowObjectRel rdaWorkflowObjectRelList:list){
                                Long objectid=rdaWorkflowObjectRelList.getObjectid();
                                Long policyid = null;
                                WorkFlowLifeCycleUtil workFlowLifeCycleUtil=null;
                                if("document".equals(rdaWorkflowObjectRelList.getObjectModuleName())){
                                    if(startStateName!=null && !"".equals(startStateName)&&EndstateName!=null && !"".equals(EndstateName)){
                                        HashMap<String,Object> documentPage=dynamicService.selectDataById("rda_document",objectid);
                                        Long documentPolocyid=Long.valueOf(documentPage.get("policyid").toString());
                                        RdaState rdaState=new RdaState();
                                        rdaState.setPolicyid(documentPolocyid);
                                        rdaState.setName(EndstateName);
                                        List<RdaState>  rdaStateList=rdaStateService.selectRdaStateList(rdaState);
                                        if(rdaStateList!=null){
                                            workFlowLifeCycleUtil = new WorkFlowLifeCycleUtil(rdaStateService,dynamicService,sysHistoryService);
                                            workFlowLifeCycleUtil.goToTargetState(objectid,documentPolocyid,operation,moduleName,rdaStateList.get(0).getId());
                                        }else{
                                            System.out.println("提升生命周期目标状态错误");
                                        }
                                    }
                                }
                                if(policyid!=null){
                                    RdaState rdaState=new RdaState();
                                    rdaState.setPolicyid(policyid);
                                    rdaState.setName(EndstateName);
                                    List<RdaState>  rdaStateList=rdaStateService.selectRdaStateList(rdaState);
                                    if(rdaStateList!=null){
                                        workFlowLifeCycleUtil.goToTargetState(objectid,policyid,operation,moduleName,rdaStateList.get(0).getId());
                                    }else{
                                        System.out.println("提升生命周期目标状态错误");
                                    }
                                }
                            }

                        }
                    }
                }
            }
            //5.循环处理下一节点（NextNode） end
        }
        //4 如果该节点被完成（NodeCheck=True），则查询该节点的下一节点(可能有多个)及相关属性 end

        //查询流程相关对象
//        RdaDocumentController rdaDocumentController=new RdaDocumentController();
        String appovedScriptTmp=rdaWfNode.getAppovedScript();
        if(appovedScriptTmp!=null && !"".equals(appovedScriptTmp)){
            String moduleName="";
            String operation="";
            String startStateName="";
            String[] appovedScriptTmp1=appovedScriptTmp.split(":");
            String[] moduleNames=appovedScriptTmp1[0].split("_");
            String EndstateName=appovedScriptTmp1[1];

            if(moduleNames.length>=3){
                moduleName=moduleNames[0];
                operation=moduleNames[1];
                int index=appovedScriptTmp1[0].indexOf("_");
                index=appovedScriptTmp.indexOf("_",index+1);
                startStateName=appovedScriptTmp1[0].substring(index).substring(1);
            }else{
                return error("提升对象生命周期配置错误!请联系系统管理员");
            }

            RdaWorkflowObjectRel rdaWorkflowObjectRel =new RdaWorkflowObjectRel();
            rdaWorkflowObjectRel.setWorkflowid(rdaWfNode.getWorkflowid());
            rdaWorkflowObjectRel.setPurpose("approve");
            rdaWorkflowObjectRel.setObjectModuleName(moduleName);
            List<RdaWorkflowObjectRel> list=rdaWorkflowObjectRelService.selectRdaWorkflowObjectRelList(rdaWorkflowObjectRel);
            for(RdaWorkflowObjectRel rdaWorkflowObjectRelList:list){
                Long objectid=rdaWorkflowObjectRelList.getObjectid();
                WorkFlowLifeCycleUtil workFlowLifeCycleUtil=null;
                Long policyId=null;
                Long stateId=null;
                if("document".equals(rdaWorkflowObjectRelList.getObjectModuleName())){
                    Long ObjectPolicyid=rdaWorkflowObjectRelList.getObjectPolicyid();
                    if(startStateName!=null && !"".equals(startStateName)&&EndstateName!=null && !"".equals(EndstateName)){
                        HashMap<String,Object> documentPage=dynamicService.selectDataById("rda_document",rdaWorkflowObjectRel.getObjectid());
                        Long documentStateid=Long.valueOf(documentPage.get("stateid").toString());
                        Long documentPolocyid=Long.valueOf(documentPage.get("policyid").toString());
                        RdaState rdaState=rdaStateService.selectRdaStateById(documentStateid);
                        if(rdaState.getName().equalsIgnoreCase(startStateName)){
                            rdaState=new RdaState();
                            rdaState.setPolicyid(documentPolocyid);
                            rdaState.setName(EndstateName);
                            List<RdaState>  rdaStateList=rdaStateService.selectRdaStateList(rdaState);
                            if(rdaStateList!=null){
                                workFlowLifeCycleUtil = new WorkFlowLifeCycleUtil(rdaStateService,dynamicService,sysHistoryService);
                                workFlowLifeCycleUtil.goToTargetState(objectid,documentPolocyid,operation,moduleName,rdaStateList.get(0).getId());
                            }else{
                                System.out.println("提升生命周期目标状态错误");
                            }
                        }
                    }else{
                        return error("提升对象生命周期配置错误!请联系系统管理员");
                    }
                }
                if(policyId!=null && stateId!=null){
                    RdaState rdaState=rdaStateService.selectRdaStateById(stateId);
                    if(rdaState.getName().equalsIgnoreCase(startStateName)){
                        rdaState=new RdaState();
                        rdaState.setPolicyid(policyId);
                        rdaState.setName(EndstateName);
                        List<RdaState>  rdaStateList=rdaStateService.selectRdaStateList(rdaState);
                        if(rdaStateList!=null){
                            AjaxResult ajaxResult=workFlowLifeCycleUtil.goToTargetState(objectid,policyId,operation,moduleName,rdaStateList.get(0).getId());
                            if(ajaxResult!=null){
                                Integer code=(Integer)ajaxResult.get("code");
                                if(code== HttpStatus.ERROR){
                                    //数据库回滚
                                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                                    return ajaxResult;
                                }
                            }
                        }else{
                            System.out.println("提升生命周期目标状态错误");
                        }
                    }
                }
            }
        }


        //如果当前流程需要完成（WorkFlowCheck=True）start
        if(WorkFlowCheck&& nextnodesize==1){
//            rdaWfNodeService.updateRdaWfNodeByToStateid(nodeIdEnd,nodeStateAppoveid);
//            rdaWfNodeService.updateRdaWfNodeByToStateid(nodeIdEnd,WorkflowStateid.wfNodeCompleteid,"批准");
            rdaWfNodeService.updateRdaWfNodeByNodeIdEnd(nodeIdEnd,WorkflowStateid.wfNodeCompleteid,"批准",DateUtils.getNowDate());
            RdaWorkflow rdaWorkflow=new RdaWorkflow();
            rdaWorkflow.setId(workflowid);
            rdaWorkflow.setStateid(WorkflowStateid.workflowCompleteid.intValue());
            rdaWorkflowService.updateRdaWorkflow(rdaWorkflow);
            historyLog(rdaWorkflow.getId(),WorkflowStateid.workflowActiveid,WorkflowStateid.workflowCompleteid,"promote");
            //当流程完成时，处理根据各个模块操作
            RdaWorkflowObjectRel rdaWorkflowObjectRel=new RdaWorkflowObjectRel();
            rdaWorkflowObjectRel.setWorkflowid(workflowid);
            List<RdaWorkflowObjectRel> moduleNameList= rdaWorkflowObjectRelService.selectRdaWorkflowObjectRelList(rdaWorkflowObjectRel);
            moduleNameList.forEach((RdaWorkflowObjectRel moduleName)->{
                if("document".equals(moduleName.getObjectModuleName())){//文档接入流程

                }
            });

        }
          return toAjax(1);
    }


    /**
     * 节点启动
     */
    public  void workflowStartUpNode(Long nextNodeId,Long workflowid){
        RdaWfNode startNode=rdaWfNodeService.selectRdaWfNodeStartOrEnd(workflowid,0l);//开始节点
        RdaWfNode rrdaWfNode=new RdaWfNode();
//        rdaWfNodeService.updateRdaWfNodeStateid(nextNodeId,WorkflowStateid.wfNodeActiveid);
        rrdaWfNode.setId(nextNodeId);
        rrdaWfNode.setStateid(WorkflowStateid.wfNodeActiveid.intValue());
        // 2022-01-15记录开始时间 start
        rrdaWfNode.setStartTime(DateUtils.getNowDate());
        // 2022-01-15记录开始时间 end
        rdaWfNodeService.updateRdaWfNode(rrdaWfNode);
        //如果下一节点(toid）被设置为活动,为toid节点的每个用户创建流程任务，节点任务表（WFTask），把每一个任务和toid节点创建关系（rel_Node2Task）节点任务关系表,最后将每一个任务设置成活动 start
        List<RdaWfNode>  list2=rdaWfNodeService.selectRdaWfNodebyUser(nextNodeId);//rda_wf_node where id=#{nextNodeId}
        if(list2!=null ){
            for (RdaWfNode rdaWfNode3:list2) {
                if(rdaWfNode3.getUserId()!=null &&rdaWfNode3.getUserId().length()>0){
                    String[] userIdI=rdaWfNode3.getUserId().split(",");
                    for(int i=0;i<userIdI.length;i++) {
                        Long getuserId = Long.valueOf(userIdI[i]);
                        RdaWfTask rdaWfTask3 = new RdaWfTask();
                        Long id = SnowFlakeUtils.nextId();
                        rdaWfTask3.setId(id);
                        rdaWfTask3.setWorkflowid(workflowid);
                        rdaWfTask3.setNodeid(rdaWfNode3.getId());
                        // 2022-01-15记录开始时间 start
                        rdaWfTask3.setStartTime(DateUtils.getNowDate());
                        // 2022-01-15记录开始时间 end
                        //2022-02-11 通过流程启动判断该流程是否是全局委托 start
                        if (workflowAgent(rdaWfNode3)) {
                            return;
                        }
                        Long userId = null;
                        //2022-02-11 通过流程启动判断该流程是否是全局委托 end
                        if (nextNodeId.equals(startNode.getId())) {
                            rdaWfTask3.setTaskName("流程被拒绝退回，请重新走流程");
                            rdaWfTask3.setDescription("流程被拒绝退回，请重新走流程");
                            rdaWfTask3.setUserId(startNode.getOwnerid());
                            rdaWfTask3.setOwnerid(SecurityUtils.getUserId());
                            /*后期需要改成动态获取 2021-12-19***/
                            rdaWfTask3.setTypeid(WorkflowStateid.wfTaskTypeid);
                            rdaWfTask3.setPolicyid(WorkflowStateid.wfTaskPolicyid);
                            rdaWfTask3.setStateid(WorkflowStateid.wfTaskActiveid);
                            rdaWfTask3.setTransfer(false);
                            if (userId != null) {
                                rdaWfTask3.setOriginalId(userId);
                                rrdaWfNode = new RdaWfNode();
                                rrdaWfNode.setId(nextNodeId);
                                rrdaWfNode.setUserId(userId.toString());
                                rdaWfNodeService.updateRdaWfNode(rrdaWfNode);
                            } else {
                                rdaWfTask3.setOriginalId(startNode.getOwnerid());
                            }
                            rdaWfTaskService.insertRdaWfTask(rdaWfTask3);
                            //还剩关系表未插入、待完成rda_node2_task_rel
                            RdaNode2TaskRel rdaNode2TaskRel = new RdaNode2TaskRel();
                            rdaNode2TaskRel.setId(SnowFlakeUtils.nextId());
                            rdaNode2TaskRel.setTaskid(rdaWfTask3.getId());
                            rdaNode2TaskRel.setNodeid(rdaWfNode3.getId());
                            rdaNode2TaskRelService.insertRdaNode2TaskRel(rdaNode2TaskRel);
                            //开始发送邮件
                      /*      SysUser sysUser = userService.selectUserById(rdaWfTask3.getOriginalId());
                            if (sysUser.getEmail() != null && sysUser.getEmail().length() > 0) {
                                String emailTitle = "你的流程任务已被驳回，请检查后重新发起流程";
                                List<EmailUser> EmailUserlList = new ArrayList<>();
                                EmailUser user = new EmailUser();
                                user.setAddress(sysUser.getEmail());
                                EmailUserlList.add(user);
                                RdaWorkflow rdaWorkflow = rdaWorkflowService.selectRdaWorkflowById(workflowid);
                                StringBuffer content = emailUtil.MailTemplate5(rdaWorkflow.getName(), "流程被拒绝退回，请重新走流程");
                                try {
                                    emailUtil.sendMail(EmailUserlList, null, null, emailTitle, content, null);
                                } catch (Exception e) {
                                    System.out.println("==========调用发送邮件错误=>>>");
                                    e.printStackTrace();
                                }
                            }*/
                            //开始发送微信消息通知
                   /*         if (sysUser.getWechat() != null && sysUser.getWechat().length() > 0) {
                                RdaWorkflow rdaWorkflow = rdaWorkflowService.selectRdaWorkflowById(workflowid);
                                StringBuffer content = new StringBuffer();
                                content.append("你的流程任务已被驳回，请登陆系统检查后重新发起流程！\n");
                                content.append("流程名称：" + rdaWorkflow.getName() + "\n");
                                content.append("流程任务名称：" + "流程被拒绝退回，请重新走流程\n");
                                content.append("url："+ mailConfig.getJumpUrl() +"/reimbursement/user/myCheckList");
                                String wechat = sysUser.getWechat();
                                String message = content.toString();
                                WeChatUtils.sendTextMessage(wechat, message);
                            }*/
                        } else {
                            rdaWfTask3.setTaskName(rdaWfNode3.getNodeName() + "的任务");
                            rdaWfTask3.setDescription(rdaWfNode3.getNodeName() + "的任务");
                            rdaWfTask3.setUserId(getuserId);
                            rdaWfTask3.setOwnerid(SecurityUtils.getUserId());
                            /*后期需要改成动态获取 2021-12-19***/
                            rdaWfTask3.setTypeid(WorkflowStateid.wfTaskTypeid);
                            rdaWfTask3.setPolicyid(WorkflowStateid.wfTaskPolicyid);
                            rdaWfTask3.setStateid(WorkflowStateid.wfTaskActiveid);
                            rdaWfTask3.setTransfer(false);
                            rdaWfTask3.setOriginalId(getuserId);
                            rdaWfTaskService.insertRdaWfTask(rdaWfTask3);
                            //还剩关系表未插入、待完成rda_node2_task_rel
                            RdaNode2TaskRel rdaNode2TaskRel = new RdaNode2TaskRel();
                            rdaNode2TaskRel.setId(SnowFlakeUtils.nextId());
                            rdaNode2TaskRel.setTaskid(rdaWfTask3.getId());
                            rdaNode2TaskRel.setNodeid(rdaWfNode3.getId());
                            rdaNode2TaskRelService.insertRdaNode2TaskRel(rdaNode2TaskRel);
                            //2022-11-07 邮件提醒功能
                      /*      if (rdaWfNode3.getEmail() != null && rdaWfNode3.getEmail().length() > 0) {
                                String emailTitle = "你有一条新的待审批的流程任务";
                                List<EmailUser> EmailUserlList = new ArrayList<>();
                                EmailUser user = new EmailUser();
                                user.setAddress(rdaWfNode3.getEmail());
                                EmailUserlList.add(user);
                                RdaWorkflow rdaWorkflow = rdaWorkflowService.selectRdaWorkflowById(workflowid);
                                StringBuffer content = emailUtil.MailTemplate4(rdaWorkflow.getName(), rdaWfNode3.getNodeName() + "的任务");
                                try {
                                    emailUtil.sendMail(EmailUserlList, null, null, emailTitle, content, null);
                                } catch (Exception e) {
                                    System.out.println("==========调用发送邮件错误=>>>");
                                    e.printStackTrace();
                                }
                            }*/
                            //开始发送微信消息通知
                         /*   SysUser sysUser = userService.selectUserById(rdaWfTask3.getUserId());
                            if (sysUser.getWechat() != null && sysUser.getWechat().length() > 0) {
                                RdaWorkflow rdaWorkflow = rdaWorkflowService.selectRdaWorkflowById(workflowid);
                                StringBuffer content = new StringBuffer();
                                content.append("你有一条新的待审批的流程任务,请登陆系统及时处理\n");
                                content.append("流程名称：" + rdaWorkflow.getName() + "\n");
                                content.append("流程任务名称：" + rdaWfNode3.getNodeName() + "的任务\n");
                                content.append("url："+ mailConfig.getJumpUrl() +"/reimbursement/user/myCheckList");
                                String wechat = sysUser.getWechat();
                                String message = content.toString();
                                WeChatUtils.sendTextMessage(wechat, message);
                            }*/
                        }
                    }
                }else {
                    RdaWfTask rdaWfTask3 = new RdaWfTask();
                    Long id = SnowFlakeUtils.nextId();
                    rdaWfTask3.setId(id);
                    rdaWfTask3.setWorkflowid(workflowid);
                    rdaWfTask3.setNodeid(rdaWfNode3.getId());
                    // 2022-01-15记录开始时间 start
                    rdaWfTask3.setStartTime(DateUtils.getNowDate());
                    // 2022-01-15记录开始时间 end
                    //2022-02-11 通过流程启动判断该流程是否是全局委托 start
                    if (workflowAgent(rdaWfNode3)) {
                        return;
                    }
                    Long userId = null;
                    //2022-02-11 通过流程启动判断该流程是否是全局委托 end
                    if (nextNodeId.equals(startNode.getId())) {
                        rdaWfTask3.setTaskName("流程被拒绝退回，请重新走流程");
                        rdaWfTask3.setDescription("流程被拒绝退回，请重新走流程");
                        rdaWfTask3.setUserId(startNode.getOwnerid());
                        rdaWfTask3.setOwnerid(SecurityUtils.getUserId());
                        /*后期需要改成动态获取 2021-12-19***/
                        rdaWfTask3.setTypeid(WorkflowStateid.wfTaskTypeid);
                        rdaWfTask3.setPolicyid(WorkflowStateid.wfTaskPolicyid);
                        rdaWfTask3.setStateid(WorkflowStateid.wfTaskActiveid);
                        rdaWfTask3.setTransfer(false);
                        if (userId != null) {
                            rdaWfTask3.setOriginalId(userId);
                            rrdaWfNode = new RdaWfNode();
                            rrdaWfNode.setId(nextNodeId);
                            rrdaWfNode.setUserId(userId.toString());
                            rdaWfNodeService.updateRdaWfNode(rrdaWfNode);
                        } else {
                            rdaWfTask3.setOriginalId(startNode.getOwnerid());
                        }
                        rdaWfTaskService.insertRdaWfTask(rdaWfTask3);
                        //还剩关系表未插入、待完成rda_node2_task_rel
                        RdaNode2TaskRel rdaNode2TaskRel = new RdaNode2TaskRel();
                        rdaNode2TaskRel.setId(SnowFlakeUtils.nextId());
                        rdaNode2TaskRel.setTaskid(rdaWfTask3.getId());
                        rdaNode2TaskRel.setNodeid(rdaWfNode3.getId());
                        rdaNode2TaskRelService.insertRdaNode2TaskRel(rdaNode2TaskRel);
                        //开始发送邮件
                  /*      SysUser sysUser = userService.selectUserById(rdaWfTask3.getOriginalId());
                        if (sysUser.getEmail() != null && sysUser.getEmail().length() > 0) {
                            String emailTitle = "你的流程任务已被驳回，请检查后重新发起流程";
                            List<EmailUser> EmailUserlList = new ArrayList<>();
                            EmailUser user = new EmailUser();
                            user.setAddress(sysUser.getEmail());
                            EmailUserlList.add(user);
                            RdaWorkflow rdaWorkflow = rdaWorkflowService.selectRdaWorkflowById(workflowid);
                            StringBuffer content = emailUtil.MailTemplate5(rdaWorkflow.getName(), "流程被拒绝退回，请重新走流程");
                            try {
                                emailUtil.sendMail(EmailUserlList, null, null, emailTitle, content, null);
                            } catch (Exception e) {
                                System.out.println("==========调用发送邮件错误=>>>");
                                e.printStackTrace();
                            }
                        }*/
                        //开始发送微信消息通知
                /*        if (sysUser.getWechat() != null && sysUser.getWechat().length() > 0) {
                            RdaWorkflow rdaWorkflow = rdaWorkflowService.selectRdaWorkflowById(workflowid);
                            StringBuffer content = new StringBuffer();
                            content.append("你的流程任务已被驳回，请登陆系统检查后重新发起流程！\n");
                            content.append("流程名称：" + rdaWorkflow.getName() + "\n");
                            content.append("流程任务名称：" + "流程被拒绝退回，请重新走流程\n");
                            content.append("url："+ mailConfig.getJumpUrl() +"/reimbursement/user/myCheckList");
                            String wechat = sysUser.getWechat();
                            String message = content.toString();
                            WeChatUtils.sendTextMessage(wechat, message);
                        }*/
                    } else {
                        rdaWfTask3.setTaskName(rdaWfNode3.getNodeName() + "的任务");
                        rdaWfTask3.setDescription(rdaWfNode3.getNodeName() + "的任务");
                        rdaWfTask3.setUserId(null);
                        rdaWfTask3.setOwnerid(SecurityUtils.getUserId());
                        /*后期需要改成动态获取 2021-12-19***/
                        rdaWfTask3.setTypeid(WorkflowStateid.wfTaskTypeid);
                        rdaWfTask3.setPolicyid(WorkflowStateid.wfTaskPolicyid);
                        rdaWfTask3.setStateid(WorkflowStateid.wfTaskActiveid);
                        rdaWfTask3.setTransfer(false);
                        rdaWfTask3.setOriginalId(null);
                        rdaWfTaskService.insertRdaWfTask(rdaWfTask3);
                        //还剩关系表未插入、待完成rda_node2_task_rel
                        RdaNode2TaskRel rdaNode2TaskRel = new RdaNode2TaskRel();
                        rdaNode2TaskRel.setId(SnowFlakeUtils.nextId());
                        rdaNode2TaskRel.setTaskid(rdaWfTask3.getId());
                        rdaNode2TaskRel.setNodeid(rdaWfNode3.getId());
                        rdaNode2TaskRelService.insertRdaNode2TaskRel(rdaNode2TaskRel);
                        //2022-11-07 邮件提醒功能
                      /*  if (rdaWfNode3.getEmail() != null && rdaWfNode3.getEmail().length() > 0) {
                            String emailTitle = "你有一条新的待审批的流程任务";
                            List<EmailUser> EmailUserlList = new ArrayList<>();
                            EmailUser user = new EmailUser();
                            user.setAddress(rdaWfNode3.getEmail());
                            EmailUserlList.add(user);
                            RdaWorkflow rdaWorkflow = rdaWorkflowService.selectRdaWorkflowById(workflowid);
                            StringBuffer content = emailUtil.MailTemplate4(rdaWorkflow.getName(), rdaWfNode3.getNodeName() + "的任务");
                            try {
                                emailUtil.sendMail(EmailUserlList, null, null, emailTitle, content, null);
                            } catch (Exception e) {
                                System.out.println("==========调用发送邮件错误=>>>");
                                e.printStackTrace();
                            }
                        }*/
                        //开始发送微信消息通知
                  /*      SysUser sysUser = userService.selectUserById(rdaWfTask3.getUserId());
                        if (sysUser.getWechat() != null && sysUser.getWechat().length() > 0) {
                            RdaWorkflow rdaWorkflow = rdaWorkflowService.selectRdaWorkflowById(workflowid);
                            StringBuffer content = new StringBuffer();
                            content.append("你有一条新的待审批的流程任务,请登陆系统及时处理\n");
                            content.append("流程名称：" + rdaWorkflow.getName() + "\n");
                            content.append("流程任务名称：" + rdaWfNode3.getNodeName() + "的任务\n");
                            content.append("url："+ mailConfig.getJumpUrl() +"/reimbursement/user/myCheckList");
                            String wechat = sysUser.getWechat();
                            String message = content.toString();
                            WeChatUtils.sendTextMessage(wechat, message);
                        }*/
                    }
                }
            }
        }
    }


    /**
     * 节点拒绝
     */
    public void nodeRefuse(Long nodeid,Long workflowid,RdaWfTask task){
        //如果拒绝选择跳过已完成节点时将当前节点设置为创建状态
        if(task.isSkipComplete()) {
            RdaWfNode rdaWfNode = new RdaWfNode();
            rdaWfNode.setId(nodeid);
            rdaWfNode.setStateid(WorkflowStateid.wfNodeCreateid.intValue());
            rdaWfNode.setResponseType("拒绝");
            rdaWfNode.setRejectSkipComplete(task.isSkipComplete());
            rdaWfNodeService.updateRdaWfNode(rdaWfNode);
        }else {
      /*      RdaWfNode rdaWfNode = new RdaWfNode();
            rdaWfNode.setId(nodeid);
//        rdaWfNode.setStateid(nodeStateAppoveid.intValue());
            rdaWfNode.setStateid(WorkflowStateid.wfNodeCompleteid.intValue());
            rdaWfNode.setResponseType("拒绝");
            rdaWfNodeService.updateRdaWfNode(rdaWfNode);*/
            rdaWfNodeService.updateRdaWfNodeByToStateid(nodeid, WorkflowStateid.wfNodeCompleteid,"拒绝");
        }
        // 查询当前节点（当前任务Task关联的节点）所关联的所有Task；并将该节点关联的其它Task中活动的Task设置为作废状态；
        RdaWfTask rdaWfTaskNodeid=new RdaWfTask();
        rdaWfTaskNodeid.setNodeid(nodeid);
//        rdaWfTaskNodeid.setStateid(taskStateActiveid);
        rdaWfTaskNodeid.setStateid(WorkflowStateid.wfTaskActiveid);
        rdaWfTaskNodeid.setWorkflowid(workflowid);
        List<RdaWfTask> rdaWfTask=rdaWfTaskService.selectRdaWfTaskByStateId(rdaWfTaskNodeid);
        for(RdaWfTask rdaWfTaskt:rdaWfTask){
//            if(rdaWfTaskt.getStateid().equals(taskStateActiveid)){
            if(rdaWfTaskt.getStateid().equals(WorkflowStateid.wfTaskActiveid)){
                RdaWfTask rdaWfTask2=new RdaWfTask();
                rdaWfTask2.setId(rdaWfTaskt.getId());
//                rdaWfTask2.setStateid(taskStateCancelid);
                rdaWfTask2.setStateid(WorkflowStateid.wfTaskObsoletedid);
                rdaWfTaskService.updateRdaWfTask(rdaWfTask2);//update rda_wf_task
            }
        }
    }
    /**
     *  将String数组转换为Long类型数组
     */
    public static Long[] StringArrayTurnLongArray(String [] strs){
        Long[] longs = new Long[strs.length]; //声明long类型的数组
        for(int i = 0;i<strs.length;i++) {
            String str = strs[i]; //将strs字符串数组中的第i个值赋值给str
            long thelong = Long.valueOf(str);//将str转换为long类型，并赋值给thelong
            longs[i] = thelong;//将thelong赋值给 longs数组中对应的地方
        }
        return longs; //返回long数组
    }


    /**
     * 查询流程模板列表
     */
    @PreAuthorize("@ss.hasPermi('pms:workflow:documentWorkflowList')")
    @GetMapping("/documentWorkflowList")
    public TableDataInfo documentWorkflowList(RdaWorkflow rdaWorkflow){
        startPage();
        List<RdaWorkflow> list=new ArrayList<RdaWorkflow>();
        RdaWorkflowObjectRel rdaWorkflowObjectRel=new RdaWorkflowObjectRel();
        rdaWorkflowObjectRel.setObjectid(Long.valueOf(rdaWorkflow.getObjectid()));

        List<RdaWorkflowObjectRel>  rdaWorkflowObjectRelList=rdaWorkflowObjectRelService.selectRdaWorkflowObjectRelList(rdaWorkflowObjectRel);//差个排序取最新数据根据时间排序
        if(!rdaWorkflowObjectRelList.isEmpty()){
            rdaWorkflowObjectRel=rdaWorkflowObjectRelList.get(0);
            rdaWorkflow=new RdaWorkflow();
            rdaWorkflow.setId(rdaWorkflowObjectRel.getWorkflowid());
            list=rdaWorkflowService.selectRdaWorkflowist(rdaWorkflow);
            return getDataTable(list);
        }
        return getDataTable(list);
    }

    /**
     * 查询流程模板节点列表
     */
    @PreAuthorize("@ss.hasPermi('pms:workflow:documentNodeList')")
    @GetMapping("/documentNodeList")
    public TableDataInfo documentNodeList(RdaWfNode rdaWfNode){
        startPage();
        List<RdaWfNode> ApproveList=new ArrayList<RdaWfNode>();
        RdaWorkflowObjectRel rdaWorkflowObjectRel=new RdaWorkflowObjectRel();
        rdaWorkflowObjectRel.setObjectid(Long.valueOf(rdaWfNode.getWorkflowid()));
        List<RdaWorkflowObjectRel>  rdaWorkflowObjectRelList=rdaWorkflowObjectRelService.selectRdaWorkflowObjectRelList(rdaWorkflowObjectRel);//差个排序取最新数据根据时间排序
        if(!rdaWorkflowObjectRelList.isEmpty()){
            rdaWorkflowObjectRel=rdaWorkflowObjectRelList.get(0);

            ApproveList=rdaWfNodeService.selectRdaWfNodeTemplete(rdaWorkflowObjectRel.getWorkflowid(),"Approve");
        }
        return getDataTable(ApproveList);
    }

    /**
     * 查询文档流程模板节点拒绝列表
     */
    @PreAuthorize("@ss.hasPermi('pms:workflow:documentNodeRefuseList')")
    @GetMapping("/documentNodeRefuseList")
    public TableDataInfo documentNodeRefuseList(RdaWfNode rdaWfNode){
        startPage();
        List<RdaWorkflow2NodeRel> list=new ArrayList<RdaWorkflow2NodeRel>();
        RdaWorkflowObjectRel rdaWorkflowObjectRel=new RdaWorkflowObjectRel();
        rdaWorkflowObjectRel.setObjectid(Long.valueOf(rdaWfNode.getWorkflowid()));
        List<RdaWorkflowObjectRel>  rdaWorkflowObjectRelList=rdaWorkflowObjectRelService.selectRdaWorkflowObjectRelList(rdaWorkflowObjectRel);//差个排序取最新数据根据时间排序
        if(!rdaWorkflowObjectRelList.isEmpty()){
            rdaWorkflowObjectRel=rdaWorkflowObjectRelList.get(0);
            list=rdaWorkflow2NodeRelService.selectRdaWorkflow2NodeRelByOperationType(rdaWorkflowObjectRel.getWorkflowid(),"Reject");
        }
        return getDataTable(list);
    }

    /**
     * 查询文档流程模板节点图列表
     */
    @PreAuthorize("@ss.hasPermi('pms:workflow:documentNodeFlowChartList')")
    @GetMapping("/documentNodeFlowChartList")
    public AjaxResult documentNodeFlowChartList(RdaWfNode rdaWfNode){
        startPage();
        Map<String,Object> info = new HashMap<>();
        RdaWorkflowObjectRel rdaWorkflowObjectRel=new RdaWorkflowObjectRel();
        rdaWorkflowObjectRel.setObjectid(Long.valueOf(rdaWfNode.getWorkflowid()));
        List<RdaWorkflowObjectRel>  rdaWorkflowObjectRelList=rdaWorkflowObjectRelService.selectRdaWorkflowObjectRelList(rdaWorkflowObjectRel);//差个排序取最新数据根据时间排序
        if(!rdaWorkflowObjectRelList.isEmpty()){
            rdaWorkflowObjectRel=rdaWorkflowObjectRelList.get(0);
            List<RdaWfNode> ApproveList=rdaWfNodeService.selectRdaWfNodeTemplete(rdaWorkflowObjectRel.getWorkflowid(),"Approve");
            List<RdaWorkflow2NodeRel> RejectList=rdaWorkflow2NodeRelService.selectRdaWorkflow2NodeRelByOperationType(rdaWorkflowObjectRel.getWorkflowid(),"Reject");
            RdaWfTask rdaWfTask=new RdaWfTask();
            rdaWfTask.setWorkflowid(rdaWorkflowObjectRel.getWorkflowid());
            List<RdaWfTask> taskList=rdaWfTaskService.selectRdaWfTaskList(rdaWfTask);

            RdaWorkflow2NodeRel rdaWorkflow2NodeRel=new RdaWorkflow2NodeRel();
            rdaWorkflow2NodeRel.setWorkflowid(rdaWorkflowObjectRel.getWorkflowid());
            List<RdaWorkflow2NodeRel> workflow2NodeRelList=rdaWorkflow2NodeRelService.selectRdaWorkflow2NodeRelAllList(rdaWorkflow2NodeRel);

            info.put("nodeList",ApproveList);
            info.put("Reject",RejectList);
            info.put("task",taskList);
            info.put("workflowPath",workflow2NodeRelList);
        }
        return AjaxResult.success(info);
    }


    /**
     * 启动流程
     */
    @PreAuthorize("@ss.hasPermi('pms:workflow:documentStartUpWorkflowList')")
    @GetMapping("/documentStartUpWorkflowList")
    @Transactional
    public AjaxResult documentStartUpWorkflowList(ServletRequest request){
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        String workflowid=httpRequest.getParameter("workflowid");

        Long[] Workflowids=new Long[1];
        RdaWorkflowObjectRel rdaWorkflowObjectRel=new RdaWorkflowObjectRel();
        rdaWorkflowObjectRel.setObjectid(Long.valueOf(workflowid));
        List<RdaWorkflowObjectRel>  rdaWorkflowObjectRelList=rdaWorkflowObjectRelService.selectRdaWorkflowObjectRelList(rdaWorkflowObjectRel);//差个排序取最新数据根据时间排序
        if(!rdaWorkflowObjectRelList.isEmpty()){
            rdaWorkflowObjectRel=rdaWorkflowObjectRelList.get(0);
            String checkTips=objectCheck(rdaWorkflowObjectRel,"文档启动流程");
            if(!checkTips.isEmpty()){
                return AjaxResult.error(checkTips);
            }
            Workflowids[0]=rdaWorkflowObjectRel.getWorkflowid();

            RdaWorkflow getStateid=rdaWorkflowService.selectRdaWorkflowById(rdaWorkflowObjectRel.getWorkflowid());
            if(getStateid==null){
                return AjaxResult.error("启动失败当前无相关流程数据");
            }
            Long stateid=getStateid.getStateid().longValue();
            if(!stateid.equals(WorkflowStateid.workflowCreateid)){
                return AjaxResult.error("当前任务已启动，请勿重复启动");
            }

            RdaWfNode wfNode=new RdaWfNode();
            wfNode.setWorkflowid(rdaWorkflowObjectRel.getWorkflowid());
            wfNode.setNodeType(1);
            List<RdaWfNode> WfNodeList=rdaWfNodeService.selectRdaWfNodeList(wfNode);
            String nodeNames="";
            for(RdaWfNode rdaWfNode:WfNodeList){
                if(rdaWfNode.getUserId()==null || "".equals(rdaWfNode.getUserId())){
                    nodeNames+=rdaWfNode.getNodeName()+",";
                }
            }
            if(!nodeNames.isEmpty()){
                return AjaxResult.error("当前任务有节点未指定用户，启动失败，未设置用户的节点名有："+nodeNames.substring(0,nodeNames.lastIndexOf(",")));
            }


            return startUpWorkflowList(Workflowids);
        }
        return error("启动失败当前无相关流程数据");

    }

    /**
     * 流程相关对象查询
     */
    @GetMapping("/docApproveList")
    public TableDataInfo docApproveList(Document document)
    {
        /*startPage();
        List<Document> list=documentService.selectDocumentByPurposeObjectid(document.getProjectid(),"approve");
        if(list!=null){
            ArrayList<RdaProjectWorkflow> projectWorkflowList=new ArrayList<RdaProjectWorkflow>();
            RdaWorkflowObjectRel rdaWorkflowObjectRel=new RdaWorkflowObjectRel();
            rdaWorkflowObjectRel.setWorkflowid(document.getProjectid());
            List<RdaWorkflowObjectRel> rdaWorkflowObjectRelList=rdaWorkflowObjectRelService.selectRdaWorkflowObjectRelList(rdaWorkflowObjectRel);
            rdaWorkflowObjectRelList.forEach((RdaWorkflowObjectRel workflowObjectRelList )->{
                if("reimbursement".equals(workflowObjectRelList.getObjectModuleName())){
                    List<RdaProjectWorkflow> projectWorkflow=rdaProjectWorkflowService.selectRdaProjectWorkflowByObject("rda_memberlist_user",document.getProjectid(),"approve");
                    projectWorkflow.forEach((RdaProjectWorkflow object)->{
                        projectWorkflowList.add(object);
                    });
                }else if("airticketApply".equals(workflowObjectRelList.getObjectModuleName())){
                    List<RdaProjectWorkflow> projectWorkflow=rdaProjectWorkflowService.selectRdaProjectWorkflowByObject("rda_airticket_apply",document.getProjectid(),"approve");
                    projectWorkflow.forEach((RdaProjectWorkflow object)->{
                        projectWorkflowList.add(object);
                    });
                }
            });
            return getDataTable(projectWorkflowList);
        }
        return getDataTable(list);*/
        return null;
    }

    /**
     * 流程参考文档查询
     */
    @GetMapping("/docReferenceList")
    public TableDataInfo docReferenceList(Document document)
    {
    /*    startPage();
        List<Document> list=documentService.selectDocumentByPurposeObjectid(document.getProjectid(),"reference");
        return getDataTable(list);*/
        return null;
    }


    /**
     * 添加已存在文档
     */
    @PreAuthorize("@ss.hasPermi('pms:workflow:addExisting')")
    @PostMapping("/addExisting")
    @Transactional
    public AjaxResult addExisting(@RequestBody Folder folder,ServletRequest request)
    {
        /*HttpServletRequest httpRequest = (HttpServletRequest) request;
        String type=httpRequest.getParameter("type");
        RdaWorkflowObjectRel rdaWorkflowObjectRel=new RdaWorkflowObjectRel();
        if("1".equals(type)){
            String docIds=folder.getIds();
            String[] ids =docIds.split(",");
            RdaFolderRel folderRel=new RdaFolderRel();
            folderRel.setFolderId(folder.getParentid());
            folderRel.setProjectId(folder.getProjectid());
            for(String id:ids){
                folderRel.setId(SnowFlakeUtils.nextId());
                folderRel.setDocId(Long.valueOf(id));
                rdaFolderRelService.insertRdaFolderRel(folderRel);
                new HistoryRecordUtil(rdaStateService,sysHistoryService).recordHistory(Long.parseLong(id),"添加附件", documentService.selectDocumentById(Long.parseLong(id)).getStateid(),"文档管理","");

                rdaWorkflowObjectRel.setWorkflowid(folder.getProjectid());
                rdaWorkflowObjectRel.setObjectid(Long.valueOf(id));
                rdaWorkflowObjectRel.setPurpose("reference");
                rdaWorkflowObjectRel.setObjectModuleName("document");
                rdaWorkflowObjectRel.setObjectTypeid(WorkflowStateid.documentTypeid);
                rdaWorkflowObjectRel.setObjectPolicyid(WorkflowStateid.documentPolicyid);
                rdaWorkflowObjectRel.setObjectStateid(WorkflowStateid.documentCreateid);
                rdaWorkflowObjectRelService.insertRdaWorkflowObjectRel(rdaWorkflowObjectRel);
            }
        }else{
            String docIds=folder.getIds();
            String[] ids =docIds.split(",");
            RdaFolderRel folderRel=new RdaFolderRel();
            folderRel.setFolderId(folder.getParentid());
            folderRel.setProjectId(folder.getProjectid());
            for(String id:ids){
                folderRel.setId(SnowFlakeUtils.nextId());
                folderRel.setDocId(Long.valueOf(id));
                rdaFolderRelService.insertRdaFolderRel(folderRel);
                new HistoryRecordUtil(rdaStateService,sysHistoryService).recordHistory(Long.parseLong(id),"添加附件", documentService.selectDocumentById(Long.parseLong(id)).getStateid(),"文档管理","");

                rdaWorkflowObjectRel.setWorkflowid(folder.getProjectid());
                rdaWorkflowObjectRel.setObjectid(Long.valueOf(id));
                rdaWorkflowObjectRel.setPurpose("approve");
                rdaWorkflowObjectRel.setObjectModuleName("document");
                rdaWorkflowObjectRel.setObjectTypeid(WorkflowStateid.documentTypeid);
                rdaWorkflowObjectRel.setObjectPolicyid(WorkflowStateid.documentPolicyid);
                rdaWorkflowObjectRel.setObjectStateid(WorkflowStateid.documentCreateid);
                rdaWorkflowObjectRelService.insertRdaWorkflowObjectRel(rdaWorkflowObjectRel);
            }
        }
        return toAjax(1);*/
        return null;
    }

    /**
     * 查询角色
     */
    @PreAuthorize("@ss.hasPermi('pms:workflow:roleList')")
    @GetMapping("/roleList")
    public TableDataInfo list(SysRole role)
    {
        startPage();
        List<SysRole> list = roleService.selectRoleList(role);
        return getDataTable(list);
    }

    /**
     * 执行中的流程
     */
    @PreAuthorize("@ss.hasPermi('pms:workflow:myWorkflowInExecutionList')")
    @GetMapping("/myWorkflowInExecutionList")
    public TableDataInfo myWorkflowInExecutionList(RdaWorkflow rdaWorkflow){
        startPage();
        return getDataTable(rdaWorkflowService.selectRdaWorkflowByStateids(SecurityUtils.getUserId(),WorkflowStateid.workflowCreateid+","+WorkflowStateid.workflowActiveid,rdaWorkflow.getSearchValue()));
    }

    /**
     * 已完成的流程
     */
    @PreAuthorize("@ss.hasPermi('pms:workflow:myWorkflowCompleteList')")
    @GetMapping("/myWorkflowCompleteList")
    public TableDataInfo myWorkflowCompleteList(RdaWorkflow rdaWorkflow){
        startPage();
        return getDataTable(rdaWorkflowService.selectRdaWorkflowByStateids(SecurityUtils.getUserId(),WorkflowStateid.workflowCompleteid+"",rdaWorkflow.getSearchValue()));
    }

    /**
     * 流程关联对象查询
     */
    @GetMapping("/workflowObjectList")
    public TableDataInfo workflowObjectList(String objectid)
    {
        startPage();
        List<Object> objectList=new ArrayList<Object>();
        RdaWfTask rdaWfTask=rdaWfTaskService.selectRdaWfTaskByid(Long.valueOf(objectid));
        Long workflowid=rdaWfTask.getWorkflowid();
        RdaWorkflowObjectRel rdaWorkflowObjectRel=new RdaWorkflowObjectRel();
        rdaWorkflowObjectRel.setWorkflowid(workflowid);
        List<RdaWorkflowObjectRel> rdaWorkflowObjectRelList=rdaWorkflowObjectRelService.selectRdaWorkflowObjectRelList(rdaWorkflowObjectRel);
        rdaWorkflowObjectRelList.forEach((RdaWorkflowObjectRel rdaWorkflowObjectRel2) -> {
            if("document".equals(rdaWorkflowObjectRel2.getObjectModuleName())){
                HashMap<String,Object> documentPage=dynamicService.selectDataById("rda_document",rdaWorkflowObjectRel2.getObjectid());
                objectList.add(documentPage);
            }
        });

        return getDataTable(objectList);
    }
    /**
     * 批量角色匹配
     */
    @PreAuthorize("@ss.hasPermi('pms:workflow:roleMatching')")
    @PostMapping("/roleMatching")
    @Transactional
    public AjaxResult roleMatching(@RequestBody List<WorkflowSharing> sharing)
    {
        int row = 0;
        for(WorkflowSharing sharingList:sharing){
            RdaWfNode rdaWfNode=new RdaWfNode();
            rdaWfNode.setId(sharingList.getIds());
            rdaWfNode.setUserId(sharingList.getUserIds().toString());
            row=rdaWfNodeService.updateRdaWfNode(rdaWfNode);
        }
        return toAjax(row);
    }

    /**
     * 校验
     *
     * @param rdaWorkflowObjectRel 节点ID
     * @param module 功能模块名
     * @return 错误提示信息
     */
    public String objectCheck(RdaWorkflowObjectRel rdaWorkflowObjectRel,String module){
        String checkTips="";
        if("document".equals(rdaWorkflowObjectRel.getObjectModuleName())){
            HashMap<String,Object> document=dynamicService.selectDataById("rda_document",rdaWorkflowObjectRel.getObjectid());
            if("文档启动流程".equals(module)){
                Long polisyId=Long.valueOf(document.get("policyid").toString());
                Long stateId=Long.valueOf(document.get("stateid").toString());
                Long objectPolisyId =rdaWorkflowObjectRel.getObjectPolicyid();
                Long objectStateId=rdaWorkflowObjectRel.getObjectStateid();
                if(polisyId.equals(objectPolisyId) && stateId.equals(objectStateId)){
                    checkTips="";
                }else{
                    checkTips="状态不满足流程启动条件";
                }
               /* if(document.getStateid().longValue()!= WorkflowStateid.documentApprovedid.longValue()){
                    checkTips="抱歉只有审批状态下才允许启动";
                }*/
            }
        }
        return checkTips;
    }

    /**
     * 提升生命周期
     */
    public String appovedScript(String appovedScriptTmp,Long workflowid){
        if(appovedScriptTmp!=null && !"".equals(appovedScriptTmp)){
            String moduleName="";
            String operation="";
            String startStateName="";
            String[] appovedScriptTmp1=appovedScriptTmp.split(":");
            String[] moduleNames=appovedScriptTmp1[0].split("_");
            String EndstateName=appovedScriptTmp1[1];

            if(moduleNames.length>=3){
                moduleName=moduleNames[0];
                operation=moduleNames[1];
                int index=appovedScriptTmp1[0].indexOf("_");
                index=appovedScriptTmp.indexOf("_",index+1);
                startStateName=appovedScriptTmp1[0].substring(index).substring(1);
            }else{
                return "提升对象生命周期配置错误!请联系系统管理员";
            }

            RdaWorkflowObjectRel rdaWorkflowObjectRel =new RdaWorkflowObjectRel();
            rdaWorkflowObjectRel.setWorkflowid(workflowid);
            rdaWorkflowObjectRel.setPurpose("approve");
            rdaWorkflowObjectRel.setObjectModuleName(moduleName);
            List<RdaWorkflowObjectRel> list=rdaWorkflowObjectRelService.selectRdaWorkflowObjectRelList(rdaWorkflowObjectRel);
            for(RdaWorkflowObjectRel rdaWorkflowObjectRelList:list){
                Long objectid=rdaWorkflowObjectRelList.getObjectid();
                WorkFlowLifeCycleUtil workFlowLifeCycleUtil=null;
                Long policyId=null;
                Long stateId=null;
                if("document".equals(rdaWorkflowObjectRelList.getObjectModuleName())){
                    Long ObjectPolicyid=rdaWorkflowObjectRelList.getObjectPolicyid();
                    if(startStateName!=null && !"".equals(startStateName)&&EndstateName!=null && !"".equals(EndstateName)){
                        HashMap<String,Object> documentService=dynamicService.selectDataById("rda_document",rdaWorkflowObjectRel.getObjectid());
                        Long documentStateid=Long.valueOf(documentService.get("stateid").toString());
                        Long documentPolocyid=Long.valueOf(documentService.get("policyid").toString());
                        RdaState rdaState=rdaStateService.selectRdaStateById(documentStateid);
                        if(rdaState.getName().equalsIgnoreCase(startStateName)){
                            rdaState=new RdaState();
                            rdaState.setPolicyid(documentPolocyid);
                            rdaState.setName(EndstateName);
                            List<RdaState>  rdaStateList=rdaStateService.selectRdaStateList(rdaState);
                            if(rdaStateList!=null){
                                workFlowLifeCycleUtil = new WorkFlowLifeCycleUtil(rdaStateService,dynamicService,sysHistoryService);
                                workFlowLifeCycleUtil.goToTargetState(objectid,documentPolocyid,operation,moduleName,rdaStateList.get(0).getId());
                            }else{
                                System.out.println("提升生命周期目标状态错误");
                            }
                        }
                    }else{
                        return "提升对象生命周期配置错误!请联系系统管理员";
                    }
                }
                if(policyId!=null && stateId!=null){
                    RdaState rdaState=rdaStateService.selectRdaStateById(stateId);
                    if(rdaState.getName().equalsIgnoreCase(startStateName)){
                        rdaState=new RdaState();
                        rdaState.setPolicyid(policyId);
                        rdaState.setName(EndstateName);
                        List<RdaState>  rdaStateList=rdaStateService.selectRdaStateList(rdaState);
                        if(rdaStateList!=null){
                            AjaxResult ajaxResult=workFlowLifeCycleUtil.goToTargetState(objectid,policyId,operation,moduleName,rdaStateList.get(0).getId());
                            if(ajaxResult!=null){
                                Integer code=(Integer)ajaxResult.get("code");
                                if(code== HttpStatus.ERROR){
                                    //数据库回滚
                                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                                    return "ajaxResult";
                                }
                            }
                        }else{
                            System.out.println("提升生命周期目标状态错误");
                        }
                    }
                }
            }
        }
        return "";
    }

    /**
     *自动节点处理
     */
    public boolean automaticNodeMethod(Long NextNode,Long workflowid,String approveExplain){
        RdaWfNode nodeEnd=rdaWfNodeService.selectRdaWfNodeStartOrEnd(workflowid,-1L);
        Long lastNodeId=nodeEnd.getId();
        RdaWfNode  nextRdaWfNode=rdaWfNodeService.selectRdaWfNodebyById(NextNode);
        Long nextStateid=nextRdaWfNode.getStateid().longValue();
        if(nextStateid.equals(WorkflowStateid.wfNodeActiveid) && nextRdaWfNode.isRejectAutomatic()){
            appovedScript(nextRdaWfNode.getAppovedScript(),nodeEnd.getWorkflowid());
            //将自动节点流程任务设置为完成状态
            rdaWfTaskService.updateRdaWfTaskByStateId(workflowid,NextNode,approveExplain,WorkflowStateid.wfTaskCompleteid,DateUtils.getNowDate());

            //将自动节点设置为完成状态
            rdaWfNodeService.updateRdaWfNodeByToStateid(NextNode, WorkflowStateid.wfNodeCompleteid,"批准");

            //根据节点id查询该节点所有下级节点
            List<RdaWorkflow2NodeRel> nextList=rdaWorkflow2NodeRelService.selectRdaWorkflow2NodeRelSubordinateAll(NextNode,"Approve");
            for (RdaWorkflow2NodeRel rdaWorkflow2NodeRel:nextList){
                NextNode=rdaWorkflow2NodeRel.getToid();

//                workflowStartUpNode(NextNode,workflowid);

                nextRdaWfNode=rdaWfNodeService.selectRdaWfNodebyById(NextNode);

                if(nextRdaWfNode.isRejectAutomatic()){
                    workflowStartUpNode(NextNode,workflowid);
                    boolean check=false;
                    //查询该节点的前置节点是否都是完成状态，如果都是完成状态则判断该下级节点是否是自动节点是自动节点则自动完成该节点跟任务
                    List<RdaWfNode> upperRdaWfNode=rdaWfNodeService.selectRdaWfNodeByFromIdList(NextNode,"Approve");
                    for(RdaWfNode rdaWfNode: upperRdaWfNode){
                        Long stateId=rdaWfNode.getStateid().longValue();
                        if(stateId.equals(WorkflowStateid.wfNodeCompleteid)){
                            check=true;
                        }
                    }
                    if(check){
                        //将自动节点流程任务设置为完成状态
                        rdaWfTaskService.updateRdaWfTaskByStateId(workflowid,NextNode,approveExplain,WorkflowStateid.wfTaskCompleteid,DateUtils.getNowDate());
                        //将自动节点设置为完成状态
                        rdaWfNodeService.updateRdaWfNodeByToStateid(NextNode, WorkflowStateid.wfNodeCompleteid,"批准");
                    }
                }else{
                    //下一节点如果不是自动节点则跳出
                    if(!lastNodeId.equals(NextNode)){
                        workflowStartUpNode(NextNode,workflowid);
                        break;
                    }
                }
                //是结束节点时将流程设置为完成状态
                if(lastNodeId.equals(NextNode)){
                    //将节点设置为完成状态
                    rdaWfNodeService.updateRdaWfNodeByToStateid(NextNode, WorkflowStateid.wfNodeCompleteid,"批准");
                    RdaWorkflow rdaWorkflow=new RdaWorkflow();
                    rdaWorkflow.setId(workflowid);
                    rdaWorkflow.setStateid(WorkflowStateid.workflowCompleteid.intValue());
                    rdaWorkflowService.updateRdaWorkflow(rdaWorkflow);
                }
            }
            return true;
        }
        return false;
    }


    /**
     * 流程回收
     */
    @PreAuthorize("@ss.hasPermi('pms:workflow:workflowRecovery')")
    @GetMapping("/workflowRecovery/{ids}")
    @Transactional
    public AjaxResult workflowRecovery(@PathVariable Long[] ids){
        for (int i=0;i<ids.length;i++) {
            RdaWorkflow rdaWorkflow=new RdaWorkflow();
            rdaWorkflow=rdaWorkflowService.selectRdaWorkflowById(ids[i]);
            Long stateid=rdaWorkflow.getStateid().longValue();
            if(stateid.equals(WorkflowStateid.workflowCreateid)){
                return error("当前流程状态已是创建状态无法进行回收");
            }
            //将流程任务设置为创建状态
            rdaWorkflow=new RdaWorkflow();
            rdaWorkflow.setId(ids[i]);
            rdaWorkflow.setStateid(WorkflowStateid.workflowCreateid.intValue());
            rdaWorkflowService.updateRdaWorkflow(rdaWorkflow);
            historyLog(rdaWorkflow.getId(),stateid,rdaWorkflow.getStateid().longValue(),"demote");


            //将流程节点活动和完成的流程节点设置为创建状态
            rdaWfNodeService.updateRdaWfNodeByStateids(ids[i],WorkflowStateid.wfNodeCreateid,WorkflowStateid.wfNodeActiveid+","+WorkflowStateid.wfNodeCompleteid);
            //将活动的流程任务设置为取消状态
            rdaWfTaskService.updateRdaWfTaskByStatis(ids[i],WorkflowStateid.wfTaskObsoletedid,""+WorkflowStateid.wfTaskActiveid);
        }
        return toAjax(1);
    }

    /**
     * 流程取消
     */
    @PreAuthorize("@ss.hasPermi('pms:workflow:workflowCancel')")
    @GetMapping("/workflowCancel/{ids}")
    @Transactional
    public AjaxResult workflowCancel(@PathVariable Long[] ids){
        //把流程和活动中的流程节点和流程任务都设置为作废状态；
        for (int i=0;i<ids.length;i++) {
            RdaWorkflow rdaWorkflow=new RdaWorkflow();
            rdaWorkflow=rdaWorkflowService.selectRdaWorkflowById(ids[i]);
            Long stateid=rdaWorkflow.getStateid().longValue();
            if(stateid.equals(WorkflowStateid.workflowCreateid)){
                return error("当前流程状态已是创建状态无法进行取消");
            }
            if(stateid.equals(WorkflowStateid.workflowCompleteid)){
                return error("当前流程流程已完成，无法取消");
            }
            rdaWorkflow=new RdaWorkflow();
            rdaWorkflow.setId(ids[i]);
            rdaWorkflow.setStateid(WorkflowStateid.workflowObsoletedid.intValue());
            rdaWorkflowService.updateRdaWorkflow(rdaWorkflow);
            historyLog(rdaWorkflow.getId(),stateid,rdaWorkflow.getStateid().longValue(),"demote");
            //将活动中的流程节点设置为作废状态
            rdaWfNodeService.updateRdaWfNodeByStateids(ids[i],WorkflowStateid.wfNodeObsoleteid,""+WorkflowStateid.wfNodeActiveid);
            //将活动中的流程任务设置为作废状态
            rdaWfTaskService.updateRdaWfTaskByStatis(ids[i],WorkflowStateid.wfTaskObsoletedid,""+WorkflowStateid.wfTaskActiveid);
        }
        return toAjax(1);
    }

    /**
     * 拒绝到开始节点降级处理
     */
    public String refuseGoToTargetStart(RdaWfNode rdaWfNode){
        String rejecttostartScript=rdaWfNode.getRejecttostartScript();
        if(rejecttostartScript!=null && !"".equals(rejecttostartScript)){
            String moduleName="";
            String operation="";
            String startStateName="";
            System.out.println("=======》》》》》"+rejecttostartScript);
            String[] appovedScriptTmp1=rejecttostartScript.split(":");
            String[] moduleNames=appovedScriptTmp1[0].split("_");
            String EndstateName=appovedScriptTmp1[1];

            if(moduleNames.length>=3){
                moduleName=moduleNames[0];
                operation=moduleNames[1];
                int index=appovedScriptTmp1[0].indexOf("_");
                index=rejecttostartScript.indexOf("_",index+1);
                startStateName=appovedScriptTmp1[0].substring(index).substring(1);
            }else{
                return "提升对象生命周期配置错误!请联系系统管理员";
            }
            RdaWorkflowObjectRel rdaWorkflowObjectRel =new RdaWorkflowObjectRel();
            rdaWorkflowObjectRel.setWorkflowid(rdaWfNode.getWorkflowid());
            rdaWorkflowObjectRel.setPurpose("approve");
            rdaWorkflowObjectRel.setObjectModuleName(moduleName);
            List<RdaWorkflowObjectRel> list=rdaWorkflowObjectRelService.selectRdaWorkflowObjectRelList(rdaWorkflowObjectRel);
            for(RdaWorkflowObjectRel rdaWorkflowObjectRelList:list){
                Long objectid=rdaWorkflowObjectRelList.getObjectid();
                Long policyId=null;
                Long stateId=null;
                WorkFlowLifeCycleUtil workFlowLifeCycleUtil=null;
                if("document".equals(rdaWorkflowObjectRelList.getObjectModuleName())){
                    if(startStateName!=null && !"".equals(startStateName)&&EndstateName!=null && !"".equals(EndstateName)){
                        HashMap<String,Object> documentPage=dynamicService.selectDataById("rda_document",rdaWorkflowObjectRelList.getObjectid());
                        Long documentStateid=Long.valueOf(documentPage.get("stateid").toString());
                        Long documentPolocyid=Long.valueOf(documentPage.get("policyid").toString());
                        RdaState rdaState=rdaStateService.selectRdaStateById(documentStateid);
                        if(rdaState.getName().equalsIgnoreCase(startStateName)){
                            rdaState=new RdaState();
                            rdaState.setPolicyid(documentPolocyid);
                            rdaState.setName(EndstateName);
                            List<RdaState>  rdaStateList=rdaStateService.selectRdaStateList(rdaState);
                            if(rdaStateList!=null){
                                workFlowLifeCycleUtil = new WorkFlowLifeCycleUtil(rdaStateService,dynamicService,sysHistoryService);
                                workFlowLifeCycleUtil.goToTargetState(objectid,documentPolocyid,operation,moduleName,rdaStateList.get(0).getId());
                            }else{
                                System.out.println("提升生命周期目标状态错误");
                            }
                        }
                    }else{
                        return "提升对象生命周期配置错误!请联系系统管理员";
                    }
                }
                if(policyId!=null && stateId!=null){
                    RdaState rdaState=rdaStateService.selectRdaStateById(stateId);
                    if(rdaState.getName().equalsIgnoreCase(startStateName)){
                        rdaState=new RdaState();
                        rdaState.setPolicyid(policyId);
                        rdaState.setName(EndstateName);
                        List<RdaState>  rdaStateList=rdaStateService.selectRdaStateList(rdaState);
                        if(rdaStateList!=null){
                            workFlowLifeCycleUtil.goToTargetState(objectid,policyId,operation,moduleName,rdaStateList.get(0).getId());
                        }else{
                            System.out.println("提升生命周期目标状态错误");
                        }
                    }
                }
            }
        }
        return "";
    }



    /**
     * 文档流程取消
     */
    @PreAuthorize("@ss.hasPermi('pms:workflow:objectWorkflowCancel')")
    @GetMapping("/objectWorkflowCancel/{ids}")
    @Transactional
    public AjaxResult objectWorkflowCancel(@PathVariable Long[] ids){
        for (int i=0;i<ids.length;i++) {
            RdaWorkflowObjectRel rdaWorkflowObjectRel=new RdaWorkflowObjectRel();
            rdaWorkflowObjectRel.setObjectid(Long.valueOf(ids[i]));
            List<RdaWorkflowObjectRel>  rdaWorkflowObjectRelList=rdaWorkflowObjectRelService.selectRdaWorkflowObjectRelList(rdaWorkflowObjectRel);
           for(RdaWorkflowObjectRel rdaWorkflowObjectRel2:rdaWorkflowObjectRelList){
               Long workflowid=rdaWorkflowObjectRel2.getWorkflowid();

               RdaWorkflow rdaWorkflow=new RdaWorkflow();
               rdaWorkflow=rdaWorkflowService.selectRdaWorkflowById(workflowid);
               Long stateid=rdaWorkflow.getStateid().longValue();
               if(stateid.equals(WorkflowStateid.workflowCreateid)){
                   return error("当前流程状态已是创建状态无法进行取消");
               }
               if(stateid.equals(WorkflowStateid.workflowCompleteid)){
                   return error("当前流程流程已完成，无法取消");
               }
               if("document".equals(rdaWorkflowObjectRel2.getObjectModuleName())){
                   HashMap<String,Object> document=dynamicService.selectDataById("rda_document",rdaWorkflowObjectRel2.getObjectid());
                   Long ownerid=Long.valueOf(document.get("ownerid").toString());
                   if(!ownerid.equals(SecurityUtils.getUserId())){
                       return error("抱歉当前数据不在你名下，你无权进行流程取消操作");
                   }
               }
               rdaWorkflow=new RdaWorkflow();
               rdaWorkflow.setId(workflowid);
               rdaWorkflow.setStateid(WorkflowStateid.workflowObsoletedid.intValue());
               rdaWorkflowService.updateRdaWorkflow(rdaWorkflow);
               historyLog(rdaWorkflow.getId(),stateid,rdaWorkflow.getStateid().longValue(),"demote");
               //将活动中的流程节点设置为作废状态
               rdaWfNodeService.updateRdaWfNodeByStateids(workflowid,WorkflowStateid.wfNodeObsoleteid,""+WorkflowStateid.wfNodeActiveid);
               //将活动中的流程任务设置为作废状态
               rdaWfTaskService.updateRdaWfTaskByStatis(workflowid,WorkflowStateid.wfTaskObsoletedid,""+WorkflowStateid.wfTaskActiveid);
               return toAjax(1);
           }
        }
        return error("程序发生未知错误请联系管理员");
    }

    /**
     * 流程回收
     */
    @PreAuthorize("@ss.hasPermi('pms:workflow:objectWorkflowRecovery')")
    @GetMapping("/objectWorkflowRecovery/{ids}")
    @Transactional
    public AjaxResult objectWorkflowRecovery(@PathVariable Long[] ids){
        for (int i=0;i<ids.length;i++) {
            RdaWorkflowObjectRel rdaWorkflowObjectRel=new RdaWorkflowObjectRel();
            rdaWorkflowObjectRel.setObjectid(Long.valueOf(ids[i]));
            List<RdaWorkflowObjectRel>  rdaWorkflowObjectRelList=rdaWorkflowObjectRelService.selectRdaWorkflowObjectRelList(rdaWorkflowObjectRel);
            for(RdaWorkflowObjectRel rdaWorkflowObjectRel2:rdaWorkflowObjectRelList){
                Long workflowid=rdaWorkflowObjectRel2.getWorkflowid();
                RdaWorkflow rdaWorkflow=new RdaWorkflow();
                rdaWorkflow=rdaWorkflowService.selectRdaWorkflowById(workflowid);
                Long stateid=rdaWorkflow.getStateid().longValue();
                if(stateid.equals(WorkflowStateid.workflowCreateid)){
                    return error("当前流程状态已是创建状态无法进行回收");
                }

                if(!stateid.equals(WorkflowStateid.workflowActiveid)){
                    return error("当前流程状态不是活动状态无法进行回收");
                }

                //节点状态活动，允许回收，可以拒绝到开始节点
                String nodeNames="";
                RdaWfNode rdaWfNode=new RdaWfNode();
                rdaWfNode.setWorkflowid(workflowid);
                rdaWfNode.setIsWithdraw("是");
                rdaWfNode.setStateid(WorkflowStateid.wfNodeActiveid.intValue());
                rdaWfNode.setRejectTostart(true);
                List<RdaWfNode> rdaWfNodeList=rdaWfNodeService.selectRdaWfNodeList(rdaWfNode);
                for(RdaWfNode wfNode:rdaWfNodeList){
                    nodeNames+=wfNode.getNodeName()+",";
                }

                if(rdaWfNodeList.isEmpty()){
                    return AjaxResult.error("当前节点不允许回收");
                }

                if("document".equals(rdaWorkflowObjectRel2.getObjectModuleName())){
                    HashMap<String,Object> document=dynamicService.selectDataById("rda_document",rdaWorkflowObjectRel2.getObjectid());
                    Long ownerid=Long.valueOf(document.get("ownerid").toString());
                    if(!ownerid.equals(SecurityUtils.getUserId())){
                        return error("抱歉当前数据不在你名下，你无权进行流程回收操作");
                    }
                }
                //5.1 查询该流程所有活动状态的任务;将所有活动状态的任务的状态修改为作废状态
                RdaWfTask rdaWfTask3=new RdaWfTask();
                rdaWfTask3.setStateid(WorkflowStateid.wfTaskActiveid);//nodeStateActiveid
                rdaWfTask3.setWorkflowid(workflowid);
                rdaWfTask3.setToolbarType("1");
                List<RdaWfTask> rdaWfTaskList=rdaWfTaskService.selectRdaWfTaskList(rdaWfTask3);//rda_wf_task where workflowid=#{workflowid} and Stateid=#{Stateid}
                for(RdaWfTask rdaWfTask4:rdaWfTaskList){
                    RdaWfTask rdaWfTask5=new RdaWfTask();
                    rdaWfTask5.setId(rdaWfTask4.getId());
                    rdaWfTask5.setStateid(WorkflowStateid.wfTaskObsoletedid);
                    rdaWfTaskService.updateRdaWfTask(rdaWfTask5);
                }
                //5.2 查询该流程所有活动状态的节点；将其状态重置为创建状态；
                RdaWfNode rdaWfNode3=new RdaWfNode();
                rdaWfNode3.setWorkflowid(workflowid);
                rdaWfNode3.setStateid(WorkflowStateid.wfNodeActiveid.intValue());
                List<RdaWfNode> rdaWfNodeActivityList=rdaWfNodeService.selectRdaWfNodeList(rdaWfNode3);//rda_wf_node where Workflowid=#{Workflowid} and Stateid=#{Stateid}
                for(RdaWfNode rdaWfNodeActivity: rdaWfNodeActivityList){
                    rdaWfNode3=new RdaWfNode();
                    rdaWfNode3.setId(rdaWfNodeActivity.getId());
                    rdaWfNode3.setStateid(WorkflowStateid.wfNodeCreateid.intValue());
                    rdaWfNodeService.updateRdaWfNode(rdaWfNode3);
                }


                //5.3 查询该流程所有完成状态的节点；将其状态重置为创建状态；
                rdaWfNode3=new RdaWfNode();
                rdaWfNode3.setWorkflowid(workflowid);
                rdaWfNode3.setStateid(WorkflowStateid.wfNodeCompleteid.intValue());
                List<RdaWfNode> rdaWfNodeCompleteList=rdaWfNodeService.selectRdaWfNodeList(rdaWfNode3);//rda_wf_node where Workflowid=#{Workflowid} and Stateid=#{Stateid}
                for (RdaWfNode rdaWfNodeComplete: rdaWfNodeCompleteList){
                    rdaWfNode3=new RdaWfNode();
                    rdaWfNode3.setId(rdaWfNodeComplete.getId());
                    rdaWfNode3.setStateid(WorkflowStateid.wfNodeCreateid.intValue());
                    // 2022-01-15 重置完成时间 start
                    rdaWfNode3.setAccomplishTime(null);
                    rdaWfNode3.setCostTimeDay(null);
                    rdaWfNodeService.updateRdaWfNodeByStartTime(rdaWfNode3);
                }

                //获取当前节点拒绝到开始节点脚本，执行降级操作
                for(RdaWfNode wfNode:rdaWfNodeList){
                    String error=refuseGoToTargetStart(wfNode);
                    if(error!="" && !"".equals(error)){
                        return error("wf1002:流程相关对象降级失败");
                    }
                }
                //将流程列表设置为创建状态
                rdaWorkflow=new RdaWorkflow();
                rdaWorkflow.setId(workflowid);
                rdaWorkflow.setStateid(WorkflowStateid.workflowCreateid.intValue());
                rdaWorkflowService.updateRdaWorkflow(rdaWorkflow);
                historyLog(rdaWorkflow.getId(),stateid,rdaWorkflow.getStateid().longValue(),"demote");

                return toAjax(1);
            }
        }
        return error("程序发生未知错误请联系管理员");
    }

    //流程委托 优先级依次为：流程指定节点委托>流程模板委托>全局委托
    public boolean workflowAgent(RdaWfNode rdaWfNode){
        //指定节点委托
        if ("是".equals(rdaWfNode.getIsAgent())) {
            //则查找对应的模板id并通过流程委托关系表进行匹配，查找是否有对应的委托人；
            RdaWfNodeAgentRel rdaWfNodeAgentRel = new RdaWfNodeAgentRel();
            rdaWfNodeAgentRel.setWorkflowtempleteid(rdaWfNode.getWorkflowtempleteid());
            rdaWfNodeAgentRel.setTempleteNodeId(rdaWfNode.getWorkflowtempleteNodeid());
            rdaWfNodeAgentRel.setEndTime(DateUtils.getNowDate());
            List<RdaWfNodeAgentRel> rdaWfNodeAgentRelList = rdaWfNodeAgentRelService.selectRdaWfNodeAgentRelList(rdaWfNodeAgentRel);
            if(rdaWfNodeAgentRelList.size()!=0) {
                for (RdaWfNodeAgentRel wfNodeAgentRel : rdaWfNodeAgentRelList) {
                    //设置流程节点委托为激活状态
                    RdaWfNodeAgentRel nodeAgentRel=new RdaWfNodeAgentRel();
                    nodeAgentRel.setId(wfNodeAgentRel.getId());
                    nodeAgentRel.setStateid(WorkflowStateid.agentNodeActivation);
                    rdaWfNodeAgentRelService.updateRdaWfNodeAgentRel(nodeAgentRel);

                    Long agentUserId = wfNodeAgentRel.getAgentUserId();//委托人id
                    Long beagentUserId = wfNodeAgentRel.getBeagentUserId();//被委托人id

                    RdaWfTask rdaWfTask = new RdaWfTask();
                    Long id = SnowFlakeUtils.nextId();
                    rdaWfTask.setId(id);
                    rdaWfTask.setWorkflowid(rdaWfNode.getWorkflowid());
                    rdaWfTask.setNodeid(rdaWfNode.getId());
                    rdaWfTask.setTaskName(rdaWfNode.getNodeName() + "的任务");
                    rdaWfTask.setDescription(rdaWfNode.getNodeName() + "的任务");

                    rdaWfTask.setOwnerid(SecurityUtils.getUserId());
                    rdaWfTask.setTypeid(WorkflowStateid.wfTaskTypeid);
                    rdaWfTask.setPolicyid(WorkflowStateid.wfTaskPolicyid);
                    rdaWfTask.setStateid(WorkflowStateid.wfTaskActiveid);
                    rdaWfTask.setTransfer(false);
                    rdaWfTask.setCreateTime(DateUtils.getNowDate());
                    rdaWfTask.setStartTime(DateUtils.getNowDate());
                    if ("替代".equals(wfNodeAgentRel.getAgentTypeid())) {
                        //流程任务直接发送给委托人，被委托人不需要看到和处理（一条任务）；
                        //将userid更改为委托人id
                        String [] userIdI=rdaWfNode.getUserId().split(",");
                        for(int i=0;i<userIdI.length;i++){
                            Long userId=Long.valueOf(userIdI[i]);
                            rdaWfTask.setUserId(agentUserId);
                            rdaWfTask.setOriginalId(userId);
                            rdaWfTask.setAgentTypeid("替代");
                            rdaWfTaskService.insertRdaWfTask(rdaWfTask);
                        }

                    } else if ("抄送".equals(wfNodeAgentRel.getAgentTypeid())) {
                        //抄送：流程任务直接发送给委托人，被委托人可以看到不需要处理（两个任务，被委托人的任务不需要也不能处理，委托人任务处理完成后被委托人任务自动完成）；
                        //生成一条委托人任务跟一条被委托人任务，被委托人任务用代理类型抄送来区分
                        String [] userIdI=rdaWfNode.getUserId().split(",");
                        for(int i=0;i<userIdI.length;i++){
                            Long userId=Long.valueOf(userIdI[i]);
                            rdaWfTask.setUserId(agentUserId);
                            rdaWfTask.setOriginalId(userId);
                            rdaWfTaskService.insertRdaWfTask(rdaWfTask);

                            rdaWfTask.setId(SnowFlakeUtils.nextId());
                            rdaWfTask.setUserId(beagentUserId);
                            rdaWfTask.setOriginalId(userId);
                            rdaWfTask.setAgentTypeid("抄送");
                            rdaWfTaskService.insertRdaWfTask(rdaWfTask);
                        }
                    } else if ("同时处理".equals(wfNodeAgentRel.getAgentTypeid())) {
                        //被委托人和委托人可以同时处理，只要有一个处理完成就可以完成（两个并行的or任务）；
                        String [] userIdI=rdaWfNode.getUserId().split(",");
                        for(int i=0;i<userIdI.length;i++){
                            Long userId=Long.valueOf(userIdI[i]);
                            rdaWfTask.setUserId(agentUserId);
                            rdaWfTask.setOriginalId(userId);
                            rdaWfTask.setAgentTypeid("同时处理");
                            rdaWfTaskService.insertRdaWfTask(rdaWfTask);

                            rdaWfTask.setId(SnowFlakeUtils.nextId());
                            rdaWfTask.setUserId(beagentUserId);
                            rdaWfTask.setOriginalId(userId);
                            rdaWfTask.setAgentTypeid("同时处理");
                            rdaWfTaskService.insertRdaWfTask(rdaWfTask);
                        }
                    }

                    RdaNode2TaskRel rdaNode2TaskRel = new RdaNode2TaskRel();
                    rdaNode2TaskRel.setId(SnowFlakeUtils.nextId());
                    rdaNode2TaskRel.setTaskid(rdaWfTask.getId());
                    rdaNode2TaskRel.setNodeid(rdaWfNode.getId());
                    rdaNode2TaskRelService.insertRdaNode2TaskRel(rdaNode2TaskRel);
                }
                return true;
            }
            return false;
        }else{
            //全局委托之指定模板委托
            RdaWfUserAgent rdaWfUserAgent=new RdaWfUserAgent();
            rdaWfUserAgent.setWorkflowtempleteid(rdaWfNode.getWorkflowtempleteid());
            rdaWfUserAgent.setEndTime(DateUtils.getNowDate());
            List<RdaWfUserAgent> List=rdaWfUserAgentService.selectRdaWfUserAgentList(rdaWfUserAgent);
            if(List.size()!=0){
                for(RdaWfUserAgent wfUserAgent:List){
                    //设置全局委托为激活状态
                    RdaWfUserAgent userAgent=new RdaWfUserAgent();
                    userAgent.setId(wfUserAgent.getId());
                    userAgent.setStateid(WorkflowStateid.agentActivationid);
                    rdaWfUserAgentService.updateRdaWfUserAgent(userAgent);
                    Long agentUserId=wfUserAgent.getAgentUserId();//委托人id
                    Long beagentUserId=wfUserAgent.getBeagentUserId();//被委托人id

                    RdaWfTask rdaWfTask = new RdaWfTask();
                    Long id = SnowFlakeUtils.nextId();
                    rdaWfTask.setId(id);
                    rdaWfTask.setWorkflowid(rdaWfNode.getWorkflowid());
                    rdaWfTask.setNodeid(rdaWfNode.getId());
                    rdaWfTask.setTaskName(rdaWfNode.getNodeName() + "的任务");
                    rdaWfTask.setDescription(rdaWfNode.getNodeName() + "的任务");

                    rdaWfTask.setOwnerid(SecurityUtils.getUserId());
                    rdaWfTask.setTypeid(WorkflowStateid.wfTaskTypeid);
                    rdaWfTask.setPolicyid(WorkflowStateid.wfTaskPolicyid);
                    rdaWfTask.setStateid(WorkflowStateid.wfTaskActiveid);
                    rdaWfTask.setTransfer(false);
                    rdaWfTask.setCreateTime(DateUtils.getNowDate());
                    rdaWfTask.setStartTime(DateUtils.getNowDate());

                    if ("替代".equals(wfUserAgent.getAgentTypeid())) {
                        //流程任务直接发送给委托人，被委托人不需要看到和处理（一条任务）；
                        //将userid更改为委托人id
                        String [] userIdI=rdaWfNode.getUserId().split(",");
                        for(int i=0;i<userIdI.length;i++){
                            Long userId=Long.valueOf(userIdI[i]);
                            rdaWfTask.setUserId(agentUserId);
                            rdaWfTask.setOriginalId(userId);
                            rdaWfTask.setAgentTypeid("替代");
                            rdaWfTaskService.insertRdaWfTask(rdaWfTask);
                        }
                    }else if ("抄送".equals(wfUserAgent.getAgentTypeid())) {
                        //抄送：流程任务直接发送给委托人，被委托人可以看到不需要处理（两个任务，被委托人的任务不需要也不能处理，委托人任务处理完成后被委托人任务自动完成）；
                        //生成一条委托人任务跟一条被委托人任务，被委托人任务用代理类型抄送来区分
                        String [] userIdI=rdaWfNode.getUserId().split(",");
                        for(int i=0;i<userIdI.length;i++){
                            Long userId=Long.valueOf(userIdI[i]);
                            rdaWfTask.setUserId(agentUserId);
                            rdaWfTask.setOriginalId(userId);
                            rdaWfTaskService.insertRdaWfTask(rdaWfTask);

                            rdaWfTask.setId(SnowFlakeUtils.nextId());
                            rdaWfTask.setUserId(beagentUserId);
                            rdaWfTask.setOriginalId(userId);
                            rdaWfTask.setAgentTypeid("抄送");
                            rdaWfTaskService.insertRdaWfTask(rdaWfTask);
                        }

                    }else if ("同时处理".equals(wfUserAgent.getAgentTypeid())) {
                        //被委托人和委托人可以同时处理，只要有一个处理完成就可以完成（两个并行的or任务）；
                        String [] userIdI=rdaWfNode.getUserId().split(",");
                        for(int i=0;i<userIdI.length;i++){
                            Long userId=Long.valueOf(userIdI[i]);
                            rdaWfTask.setUserId(agentUserId);
                            rdaWfTask.setOriginalId(userId);
                            rdaWfTask.setAgentTypeid("同时处理");
                            rdaWfTaskService.insertRdaWfTask(rdaWfTask);

                            rdaWfTask.setId(SnowFlakeUtils.nextId());
                            rdaWfTask.setUserId(beagentUserId);
                            rdaWfTask.setOriginalId(userId);
                            rdaWfTask.setAgentTypeid("同时处理");
                            rdaWfTaskService.insertRdaWfTask(rdaWfTask);
                        }

                    }

                    RdaNode2TaskRel rdaNode2TaskRel = new RdaNode2TaskRel();
                    rdaNode2TaskRel.setId(SnowFlakeUtils.nextId());
                    rdaNode2TaskRel.setTaskid(rdaWfTask.getId());
                    rdaNode2TaskRel.setNodeid(rdaWfNode.getId());
                    rdaNode2TaskRelService.insertRdaNode2TaskRel(rdaNode2TaskRel);
                }
                return true;
            }else{
                //全局委托
                List<RdaWfUserAgent> rdaWfUserAgentList=rdaWfUserAgentService.selectRdaWfUserAgentByWorkflowtempleteid();
                if(rdaWfUserAgentList.size()!=0){
                    for(RdaWfUserAgent wfUserAgent:rdaWfUserAgentList){
                        //设置全局委托为激活状态
                        RdaWfUserAgent userAgent=new RdaWfUserAgent();
                        userAgent.setId(wfUserAgent.getId());
                        userAgent.setStateid(WorkflowStateid.agentActivationid);
                        rdaWfUserAgentService.updateRdaWfUserAgent(userAgent);
                        Long agentUserId=wfUserAgent.getAgentUserId();//委托人id
                        Long beagentUserId=wfUserAgent.getBeagentUserId();//被委托人id

                        RdaWfTask rdaWfTask = new RdaWfTask();
                        Long id = SnowFlakeUtils.nextId();
                        rdaWfTask.setId(id);
                        rdaWfTask.setWorkflowid(rdaWfNode.getWorkflowid());
                        rdaWfTask.setNodeid(rdaWfNode.getId());
                        rdaWfTask.setTaskName(rdaWfNode.getNodeName() + "的任务");
                        rdaWfTask.setDescription(rdaWfNode.getNodeName() + "的任务");

                        rdaWfTask.setOwnerid(SecurityUtils.getUserId());
                        rdaWfTask.setTypeid(WorkflowStateid.wfTaskTypeid);
                        rdaWfTask.setPolicyid(WorkflowStateid.wfTaskPolicyid);
                        rdaWfTask.setStateid(WorkflowStateid.wfTaskActiveid);
                        rdaWfTask.setTransfer(false);
                        rdaWfTask.setCreateTime(DateUtils.getNowDate());
                        rdaWfTask.setStartTime(DateUtils.getNowDate());

                        if ("替代".equals(wfUserAgent.getAgentTypeid())) {
                            //流程任务直接发送给委托人，被委托人不需要看到和处理（一条任务）；
                            //将userid更改为委托人id
                            String [] userIdI=rdaWfNode.getUserId().split(",");
                            for(int i=0;i<userIdI.length;i++){
                                Long userId=Long.valueOf(userIdI[i]);
                                rdaWfTask.setUserId(agentUserId);
                                rdaWfTask.setOriginalId(userId);
                                rdaWfTask.setAgentTypeid("替代");
                                rdaWfTaskService.insertRdaWfTask(rdaWfTask);
                            }
                        }else if ("抄送".equals(wfUserAgent.getAgentTypeid())) {
                            //抄送：流程任务直接发送给委托人，被委托人可以看到不需要处理（两个任务，被委托人的任务不需要也不能处理，委托人任务处理完成后被委托人任务自动完成）；
                            //生成一条委托人任务跟一条被委托人任务，被委托人任务用代理类型抄送来区分
                            String [] userIdI=rdaWfNode.getUserId().split(",");
                            for(int i=0;i<userIdI.length;i++){
                                Long userId=Long.valueOf(userIdI[i]);
                                rdaWfTask.setUserId(agentUserId);
                                rdaWfTask.setOriginalId(userId);
                                rdaWfTaskService.insertRdaWfTask(rdaWfTask);

                                rdaWfTask.setId(SnowFlakeUtils.nextId());
                                rdaWfTask.setUserId(beagentUserId);
                                rdaWfTask.setOriginalId(userId);
                                rdaWfTask.setAgentTypeid("抄送");
                                rdaWfTaskService.insertRdaWfTask(rdaWfTask);
                            }
                        }else if ("同时处理".equals(wfUserAgent.getAgentTypeid())) {
                            //被委托人和委托人可以同时处理，只要有一个处理完成就可以完成（两个并行的or任务）；
                            String [] userIdI=rdaWfNode.getUserId().split(",");
                            for(int i=0;i<userIdI.length;i++){
                                Long userId=Long.valueOf(userIdI[i]);
                                rdaWfTask.setUserId(agentUserId);
                                rdaWfTask.setOriginalId(userId);
                                rdaWfTask.setAgentTypeid("同时处理");
                                rdaWfTaskService.insertRdaWfTask(rdaWfTask);

                                rdaWfTask.setId(SnowFlakeUtils.nextId());
                                rdaWfTask.setUserId(beagentUserId);
                                rdaWfTask.setOriginalId(userId);
                                rdaWfTask.setAgentTypeid("同时处理");
                                rdaWfTaskService.insertRdaWfTask(rdaWfTask);
                            }
                        }

                        RdaNode2TaskRel rdaNode2TaskRel = new RdaNode2TaskRel();
                        rdaNode2TaskRel.setId(SnowFlakeUtils.nextId());
                        rdaNode2TaskRel.setTaskid(rdaWfTask.getId());
                        rdaNode2TaskRel.setNodeid(rdaWfNode.getId());
                        rdaNode2TaskRelService.insertRdaNode2TaskRel(rdaNode2TaskRel);
                    }
                    return true;
                }
                return false;
            }
        }
    }

    /**
     * 流程分支
     */
    public ArrayList<RdaWorkflow2NodeRel> workflowBranch(List<RdaWorkflow2NodeRel> rdaWorkflow2NodeRel,String approveType){
        boolean check=false;
        ArrayList<RdaWorkflow2NodeRel> nextNodeIdList=new ArrayList<RdaWorkflow2NodeRel>();
        ArrayList<Long> nodeidList=new ArrayList<Long>();
        for(RdaWorkflow2NodeRel workflow2NodeRel:rdaWorkflow2NodeRel){
            if(workflow2NodeRel.getRoad()!=null && workflow2NodeRel.getRoad().length()>0){
                if("人工路径".equals(workflow2NodeRel.getRoad())){
                    String id[]=approveType.split("_");
                    String approveId=id[1];
                    String relId=id[2];
                    if(Long.valueOf(relId).equals(workflow2NodeRel.getId()) && workflow2NodeRel.getToid().equals(Long.valueOf(approveId))){
                        nextNodeIdList.add(workflow2NodeRel);
                    }else{
                        rdaWfNodeService.updateRdaWfNodeStateid(workflow2NodeRel.getToid(), WorkflowStateid.wfNodeObsoleteid);
                    }
                }else if("自动路径".equals(workflow2NodeRel.getRoad())){
                    /*
                    * 如果“是否自动路径”为是，则进行自动逻辑处理。查询路径属性中的表达式（例如attribute:securitylevel==SecurityTwo），
                    * 首先取“:”前的字段，如果是attribute则表示为属性值判断，再取到“==”前的属性和“==”后的路径属性值（注意去掉前后空格），
                    * 然后查询流程对象的该属性的属性值是否等于配置中定义的路径属性值；如果等于则把下级节点收集到需要启动的下层节点集合中去；
                    * */
                    String roadAttribute=workflow2NodeRel.getRoadAttribute().trim();
                    String attributeStr[]=roadAttribute.split(":");
                    String attribute=attributeStr[0];
                    String attributeArray []=attributeStr[1].split("==");
                    String attribute2=attributeArray[0];
                    String attribute3=attributeArray[1];
                    if("attribute".equals(attribute)){
                        //根据流程id查询流程对象表获取objectid查询文档表获取保密等级
                        RdaWorkflowObjectRel rdaWorkflowObjectRel=new RdaWorkflowObjectRel();
                        rdaWorkflowObjectRel.setWorkflowid(workflow2NodeRel.getWorkflowid());
                        List<RdaWorkflowObjectRel> workflowObjectRel=rdaWorkflowObjectRelService.selectRdaWorkflowObjectRelList(rdaWorkflowObjectRel);
                        if(workflowObjectRel!=null && workflowObjectRel.size()!=0){
                            if("document".equals(workflowObjectRel.get(0).getObjectModuleName())){
                                HashMap<String,Object> document=dynamicService.selectDataById("rda_document",workflowObjectRel.get(0).getObjectid());
                                String securityLevel=(String)document.get("securitylevel");
                                if(attribute3.equals(securityLevel)){
                                    nextNodeIdList.add(workflow2NodeRel);
                                    check=true;
                                }else{
                                    nodeidList.add(workflow2NodeRel.getToid());
                                }
                            }
                        }
                    }
                }
            }
        }
       if(check){
           for(Long toid:nodeidList){
               rdaWfNodeService.updateRdaWfNodeStateid(toid, WorkflowStateid.wfNodeObsoleteid);
           }
       }else{
           for(RdaWorkflow2NodeRel workflow2NodeRel:rdaWorkflow2NodeRel){
               if("自动路径".equals(workflow2NodeRel.getRoad())){
                   //流程属性没一个能匹配上直接手动抛出异常
                   throw new RuntimeException("流程分支配置有误请联系管理员");
               }
           }
       }
        return nextNodeIdList;
    }

    /**
     * 写入历史记录
     * **/
    public void historyLog(Long id,Long startStateid,Long EndStateid,String event){
//        new HistoryRecordUtil(rdaStateService,sysHistoryService).lifeCycleHistory(id,startStateid.intValue(),EndStateid.intValue(),event);
    }

    /**
     * 已取消的流程
     */
    @PreAuthorize("@ss.hasPermi('pms:workflow:myWorkflowCancelList')")
    @GetMapping("/myWorkflowCancelList")
    public TableDataInfo myWorkflowCancelList(RdaWorkflow rdaWorkflow){
        startPage();
        return getDataTable(rdaWorkflowService.selectRdaWorkflowByStateids(SecurityUtils.getUserId(),WorkflowStateid.workflowObsoletedid+"",rdaWorkflow.getSearchValue()));
    }

    /**
     * 流程恢复
     */
    @PreAuthorize("@ss.hasPermi('pms:workflow:objectWorkflowRestore')")
    @GetMapping("/objectWorkflowRestore/{ids}")
    @Transactional
    public AjaxResult objectWorkflowRestore(@PathVariable Long[] ids){
        int rows=0;
        for(int i=0;i<ids.length;i++){
            RdaWorkflow workflow=rdaWorkflowService.selectRdaWorkflowById(ids[i]);
            if(!WorkflowStateid.workflowObsoletedid.equals(workflow.getStateid().longValue())){
                return error("抱歉只有作废状态才允许流程恢复");
            }
            //将流程任务设置为活动状态
            RdaWorkflow rdaWorkflow=new RdaWorkflow();
            rdaWorkflow.setId(ids[i]);
            rdaWorkflow.setStateid(WorkflowStateid.workflowActiveid.intValue());
            rows=rdaWorkflowService.updateRdaWorkflow(rdaWorkflow);

            //根据流程id查询作废状态流程任务获取流程任务相关信息
            RdaWfTask rdaWfTask=new RdaWfTask();
            rdaWfTask.setWorkflowid(ids[i]);
            rdaWfTask.setToolbarType("1");
            rdaWfTask.setStateid(WorkflowStateid.wfTaskObsoletedid);
            List<RdaWfTask> rdaWfTaskList=rdaWfTaskService.selectRdaWfTaskList(rdaWfTask);
            Long workflowid=ids[i];
            rdaWfTaskList.forEach((RdaWfTask wfTask)-> {
                //将流程任务设置为活动状态
                RdaWfTask rdaWfTask2=new RdaWfTask();
                rdaWfTask2.setId(wfTask.getId());
                rdaWfTask2.setStateid(WorkflowStateid.wfTaskActiveid);
                rdaWfTaskService.updateRdaWfTaskAll(rdaWfTask2);

                //将流程节点设置为活动状态
                RdaWfNode rdaWfNode=new RdaWfNode();
                rdaWfNode.setId(wfTask.getNodeid());
                rdaWfNode.setWorkflowid(workflowid);
                rdaWfNode.setStateid(WorkflowStateid.wfNodeActiveid.intValue());
                rdaWfNodeService.updateRdaWfNode(rdaWfNode);
            });

        }
        return toAjax(rows);
    }

    /**
     * 流程属性、函数
     */
    public boolean condition(RdaWfNode rdaWfNextNode){
        ArrayList<String> list=new ArrayList<String>();
        if(rdaWfNextNode.getScript1()!=null&&rdaWfNextNode.getScript1().length()>0){
            list.add(rdaWfNextNode.getScript1());
        }

        if(rdaWfNextNode.getScript2()!=null&&rdaWfNextNode.getScript2().length()>0){
            list.add(rdaWfNextNode.getScript2());
        }

        if(rdaWfNextNode.getScript3()!=null&&rdaWfNextNode.getScript3().length()>0){
            list.add(rdaWfNextNode.getScript3());
        }

        if(rdaWfNextNode.getScript4()!=null&&rdaWfNextNode.getScript4().length()>0){
            list.add(rdaWfNextNode.getScript4());
        }

        if(rdaWfNextNode.getScript5()!=null&&rdaWfNextNode.getScript5().length()>0){
            list.add(rdaWfNextNode.getScript5());
        }
       return conditionCheck(list,rdaWfNextNode);
    }

    /**
     * 流程属性、函数
     */
    public boolean conditionCheck(ArrayList<String> scripts,RdaWfNode rdaWfNextNode){
        boolean check=false;
        String  attributes="";

        for(String script:scripts){
            String attributeStr[]=script.split(":");
            String attribute=attributeStr[0];
            if("attribute".equals(attribute)) {//属性
                String attributeArray []=attributeStr[1].split("==");
                String attributeName=attributeArray[0];
                String attributeValue=attributeArray[1];
                attributes+=attributeName+"='"+attributeValue+"' and ";
            }else if("program".equals(attribute)){//函数
                String programArray []=attributeStr[1].split("==");
                String programName=programArray[0];
                String functionString=programArray[1];
                goToFunction(programName,functionString);
            }
        }

        RdaWorkflowObjectRel rdaWorkflowObjectRel=new RdaWorkflowObjectRel();
        rdaWorkflowObjectRel.setWorkflowid(rdaWfNextNode.getWorkflowid());
        List<RdaWorkflowObjectRel> workflowObjectRel=rdaWorkflowObjectRelService.selectRdaWorkflowObjectRelList(rdaWorkflowObjectRel);
        if(workflowObjectRel!=null && workflowObjectRel.size()!=0){
            if("document".equals(workflowObjectRel.get(0).getObjectModuleName())){
                if(attributes!=null && attributes.length()>0){
                    attributes+="id="+workflowObjectRel.get(0).getObjectid()+"";
                    /*Document document=documentService.selectDocumentBySql(attributes);
                    if(document!=null){
                        check=true;
                        return check;
                    }*/
                }
            }
        }
        return check;
    }

    public AjaxResult goToFunction(String programName,String functionString){
        if("document".equalsIgnoreCase(programName)){//程序名
            return AjaxResult.error("函数");
        }else{
            return AjaxResult.error( "出现未知错误,请联系管理员!");
        }
    }

    /**
     * 流程恢复查询
     */
    @PreAuthorize("@ss.hasPermi('pms:workflow:documentWorkflowRecovery')")
    @GetMapping("/documentWorkflowRecovery")
    public TableDataInfo documentWorkflowRecovery(RdaWorkflow rdaWorkflow){
        startPage();
        List<RdaWorkflow> list=new ArrayList<RdaWorkflow>();
        RdaWorkflowObjectRel rdaWorkflowObjectRel=new RdaWorkflowObjectRel();
        rdaWorkflowObjectRel.setObjectid(Long.valueOf(rdaWorkflow.getObjectid()));

        List<RdaWorkflowObjectRel>  rdaWorkflowObjectRelList=rdaWorkflowObjectRelService.selectRdaWorkflowObjectRelList(rdaWorkflowObjectRel);//差个排序取最新数据根据时间排序
        if(!rdaWorkflowObjectRelList.isEmpty()){
            rdaWorkflowObjectRel=rdaWorkflowObjectRelList.get(0);
            rdaWorkflow=new RdaWorkflow();
            rdaWorkflow.setId(rdaWorkflowObjectRel.getWorkflowid());
            rdaWorkflow.setStateid(WorkflowStateid.workflowObsoletedid.intValue());
            list=rdaWorkflowService.selectRdaWorkflowist(rdaWorkflow);
            return getDataTable(list);
        }
        return getDataTable(list);
    }
}
